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;
    }
}
相关推荐
梓䈑2 小时前
【算法题攻略】BFS 解决FloodFill 算法、最短路问题、多源BFS 和 拓扑排序
c++·算法·宽度优先
Adios7945 小时前
设置交集大小至少为2
数据结构·算法·leetcode
来一碗刘肉面11 小时前
栈的应用(表达式求值)
数据结构·算法
xiaowang1234shs12 小时前
怪兽轻断食技术深度测评:从断食计时引擎到AI识别算法的工程实践解析
数据库·人工智能·算法·macos·机器学习·p2p·visual studio
小果因子实验室12 小时前
量化研究--策略迁移算法1研究
算法
Web极客码13 小时前
如何用三段式确定性剪枝,为 LLM Agent 砍掉 35% 的 Token 成本?
服务器·人工智能·算法·机器学习
程序猿乐锅13 小时前
【数据结构与算法 | 第六篇】力扣1109,1094差分数组
java·算法·leetcode
wabs66614 小时前
关于图论【广度优先搜索的理论基础】
算法·图论·宽度优先
孤魂23314 小时前
逻辑回归算法
算法·机器学习·逻辑回归