739.每日温度(中等)

思路:

观察给出的例子:

给定一个列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73],输出应该是 [1, 1, 4, 2, 1, 1, 0, 0]

从前遍历到后,若温度大于前一个,就把前一个弹出,并保存现在下标-前一个值下标的值,最后把当前下标存入栈中,很明显利用的是单调栈

class Solution {
    public int[] dailyTemperatures(int[] T) {
		int n=T.length;
		Deque<Integer> stack=new ArrayDeque<>();
		int[] ans=new int[n];
		
		for(int i=0;i<n;i++){
                        //注意:存入stack的是下标
			while(!stack.isEmpty()&&T[i]>T[stack.peekLast()]){
				int j=stack.removeLast();
				ans[j]=i-j;
			}

			//要在把所有<temp的温度弹出后才能把temp压入栈中
			//还包含了一层意思,如果不满足while的条件,也就是
			//temp<stack.peek()也压入栈中
			stack.addLast(i);
		}
		
		return ans;
	}
}

猜你喜欢

转载自blog.csdn.net/di_ko/article/details/115043216