算法练习题06:leetcode793每日温度

单调栈解法

复制代码
class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        int length = temperatures.length;
        int[] ans = new int[length];
        Stack<Integer> stack = new Stack<>();
        for(int i = 0;i<length;i++){
            int temperature = temperatures[i];
            while(!stack.isEmpty()&&temperature>temperatures[stack.peek()]){
                int pre = stack.pop();
                ans[pre] = i - pre;
            }
            stack.push(i);
        }
        return ans;
    }
}

不管咋样反正栈为空就先入栈,然后栈中存的是数组中数的索引,遍历这个数组,如果下一个数字比栈顶索引在数组中的值小,那么继续push压入栈,反之,下一个数字比栈顶索引在数组中的值大,那么就达成我们的目的了,找到比栈顶大的数了,那么pop弹出栈顶,i与弹出的那个索引做差值,就是弹出元素索引处的目标值,就是我们要的。画图看的更清楚。

相关推荐
孤飞2 小时前
zero2Agent:面向大厂面试的 Agent 工程教程,从概念到生产的完整学习路线
算法
技术专家3 小时前
Stable Diffusion系列的详细讨论 / Detailed Discussion of the Stable Diffusion Series
人工智能·python·算法·推荐算法·1024程序员节
dllxhcjla4 小时前
微服务全套
java
csdn_aspnet4 小时前
C# (QuickSort using Random Pivoting)使用随机枢轴的快速排序
数据结构·算法·c#·排序算法
亚历克斯神4 小时前
JVM 内存管理 2026:深度解析与调优实战
java·spring·微服务
鹿角片ljp4 小时前
最长回文子串(LeetCode 5)详解
算法·leetcode·职场和发展
逻辑驱动的ken5 小时前
Java高频面试题:03
java·开发语言·面试·求职招聘·春招
广师大-Wzx5 小时前
一篇文章看懂MySQL数据库(下)
java·开发语言·数据结构·数据库·windows·python·mysql
野生技术架构师5 小时前
Java NIO到底是个什么东西?
java·开发语言·nio
paeamecium6 小时前
【PAT甲级真题】- Cars on Campus (30)
数据结构·c++·算法·pat考试·pat