【队列 &栈】day20_739. 每日温度

53 阅读1分钟

给定一个整数数组 temperatures ,表示每天的温度,返回一个数组 answer ,其中 answer[i] 是指对于第 i 天,下一个更高温度出现在几天后。如果气温在这之后都不会升高,请在该位置用 0 来代替。

示例 1:

输入: temperatures = [73,74,75,71,69,72,76,73]
输出: [1,1,4,2,1,1,0,0]

示例 2:

输入: temperatures = [30,40,50,60]
输出: [1,1,1,0]

示例 3:

输入: temperatures = [30,60,90]
输出: [1,1,0]

提示:

  • 1 <= temperatures.length <= 105
  • 30 <= temperatures[i] <= 100

题解:

思路:单调递增栈

1.遍历入栈,当前元素大于栈顶元素top时,出栈,此时answer[top[0]] = i - top[0],否则直接入栈

2.遍历完成后,需要考虑栈不为空的情况

时间复杂度:O(n)

空间复杂度:O(n)

class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        Deque<int[]> stack = new LinkedList<>();
        int[] answer  = new int[temperatures.length];

        for(int i = 0; i < temperatures.length; i++){
            // stack为空时直接入栈
            if(stack.isEmpty()){
                stack.offer(new int[]{i, temperatures[i]});
                continue;
            }

            // 当前元素大于栈顶元素时,出栈
            while(stack.peekLast() != null && temperatures[i] > (stack.peekLast())[1]){
                // 出栈
                int[] top = stack.pollLast();
                answer[top[0]] = i - top[0];
            }

            stack.offer(new int[]{i, temperatures[i]});
        }

        // 栈不为空
        while(!stack.isEmpty()){
            int[] top = stack.pollLast();
            answer[top[0]] = 0;
        }

        return answer;
    }
}