美文网首页数据结构和算法
栈 - LeetCode 739.每日温度

栈 - LeetCode 739.每日温度

作者: 我阿郑 | 来源:发表于2023-11-29 18:10 被阅读0次

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

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

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

解题方案: 单调栈+下标差

class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        int[] answer = new int[temperatures.length];
        // 注意stack里存的是元素的下标
        Deque<Integer> stack = new LinkedList<Integer>();
        for(int i=0; i<temperatures.length;i++) {
            int temperature = temperatures[i];
            // 注意这里是while循环
            while(!stack.isEmpty() && temperature > temperatures[stack.peek()]) {
                int prevIndex = stack.pop();
                answer[prevIndex] = i - prevIndex;
            }
            stack.push(i);
        }
        return answer;
    }
}

注意,answer初始化完,其实它元素默认都是0

image.png

这里方便观看,把0先都去掉了

image.png
image.png
image.png
image.png

所以,answer最后结果是:

image.png

相关文章

  • 739. 每日温度

    739. 每日温度[https://leetcode.cn/problems/daily-temperatures...

  • LeetCode 739. 每日温度 | Python

    739. 每日温度 题目来源:力扣(LeetCode)https://leetcode-cn.com/proble...

  • 739. 每日温度

    739. 每日温度[https://leetcode-cn.com/problems/daily-temperat...

  • 739. 每日温度

    739. 每日温度[https://leetcode-cn.com/problems/daily-temperat...

  • 题739

    739. 每日温度[https://leetcode-cn.com/problems/daily-temperat...

  • 739. 每日温度/46. 全排列

    739. 每日温度 相关标签 : 哈希表 栈 46. 全排列 相关标签: 回溯算法

  • 单调栈

    对应力扣题目-739. 每日温度 什么是单调栈? 单调递增栈,从栈底到栈顶依次递增(单调非递减栈:允许有相等) 单...

  • leetcode - 739. 每日温度

    题目 解法一: 思路:输出的最后一位一定是0,从右往左遍历温度表T,如果当前温度T[i]小于上一次温度T[i + ...

  • LeetCode 739. 每日温度

    题目 给定一个整数数组 temperatures ,表示每天的温度,返回一个数组 answer ,其中 answe...

  • LeetCode-python 739.每日温度

    题目链接难度:中等 类型: 根据每日 气温 列表,请重新生成一个列表,对应位置的输入是你需要再等待...

网友评论

    本文标题:栈 - LeetCode 739.每日温度

    本文链接:https://www.haomeiwen.com/subject/ehkfgdtx.html