LeetCode 739. 每日温度

解题思路

单调栈的经典题型。

我们需要找到temperaturesi的右边最近的小于temperaturesi的值,所以就想到了单调栈。

相关代码

复制代码
class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        Stack<Integer> stack = new Stack<>();
        int res[] = new int[temperatures.length];
        int n = temperatures.length;
        for(int i=n-1;i>=0;i--){
            //进行筛选
            while(stack.isEmpty()==false&&temperatures[i]>=temperatures[stack.peek()]) stack.pop();
            if(stack.isEmpty()==true) res[i]=0;
            else res[i]=Math.abs(stack.peek()-i);
            stack.push(i);
        }
        return res;
    }
}
相关推荐
c238563 小时前
Bug 猎手入门指南
c++·算法·bug
Reart3 小时前
Leetcode 213.打家劫舍2(内含闲谈,打劫真是技术活,好题,716)
后端·算法
Reart4 小时前
Leetcode 198.打家劫舍(716)
后端·算法
Jerry4 小时前
LeetCode 110. 平衡二叉树
算法
玖玥拾4 小时前
C++ 数据结构 八大基础排序算法专题
数据结构·c++·算法·排序算法
Tim_105 小时前
【C++】017、new/delete与malloc/free的区别
java·数据结构·算法
从零开始的代码生活_5 小时前
C++ list 原理与实践:双向链表、迭代器与简化实现
开发语言·c++·后端·学习·算法·链表·list
ttod_qzstudio6 小时前
【软考算法】软件设计师下午第四题之动态规划:0-1 背包与最长公共子序列的“填表艺术“
算法·动态规划·软考
柒和远方6 小时前
LeetCode 139. 单词拆分 —— 从暴力回溯到 DP 完全背包
javascript·python·算法
从零开始的代码生活_7 小时前
C++ stack、queue 与 priority_queue:容器适配器原理与实战
开发语言·c++·后端·学习·算法