🌕 739. 每日温度

吞佛童子2022年6月20日
  • algorithm
  • stack
小于 1 分钟

🌕 739. 每日温度

难度: 🌕

问题描述

img_17.png


解法

class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        // 思路:
        // 单调栈 - 画图理解
        // 构造 非严格递减栈
        LinkedList<Integer> stack = new LinkedList<>(); // 存放的是数组下标
        int len = temperatures.length;
        int[] res = new int[len];
        for(int i = 0; i < len; i ++) {
            if(stack.isEmpty()) {
                stack.push(i);
            } else {
                // 栈 非空,判断是弹栈还是继续压栈
                int peekIndex = stack.peek();
                int peekTemp = temperatures[peekIndex];
                int curTemp = temperatures[i];
                if(curTemp <= peekTemp) {
                    stack.push(i);
                } else {
                    // 弹栈,直到无法继续弹栈
                    while(!stack.isEmpty() && curTemp > temperatures[stack.peek()]) {
                        int resIndex = stack.pop();
                        res[resIndex] = i - resIndex;
                    }
                    stack.push(i);
                }
            }
        }
        return res;
    }
}

输出

img_16.png

上次编辑于: 2022/10/10 下午8:43:48
贡献者: liuxianzhishou