0
点赞
收藏
分享

微信扫一扫

LeetCode 739.每日温度 - 单调栈问题

宁静的猫 2022-04-04 阅读 44
leetcode

 链接:https://leetcode-cn.com/problems/daily-temperatures/

思路:维持一个单调递减栈。

        对于每一个位置 i 的状态更新 -》 只有出现第一个大于 i 的值的时候才会开始更新。

 

class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        // 单调栈问题:如果递增可以直接更新答案;否则应该压栈等待第一个大于栈顶的元素
        Stack<Integer> stack = new Stack<>();
        int len = temperatures.length;
        stack.push(0);
        int l = 1;
        int[] anwsers = new int[temperatures.length];
        for (int i = 1; i < len; i++) {
            // 更新栈中的状态,出栈
            while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) {
                anwsers[stack.peek()] = i - stack.pop();
            }
            // 压栈
            stack.push(i);
        }
        return anwsers;
    }
}
举报

相关推荐

0 条评论