算法练习题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与弹出的那个索引做差值,就是弹出元素索引处的目标值,就是我们要的。画图看的更清楚。

相关推荐
96773 小时前
springMVC请求处理全过程
java
gelald3 小时前
Spring - 事务管理
java·后端·spring
橘子编程3 小时前
编译原理:从理论到实战全解析
java·linux·python·ubuntu
xuhaoyu_cpp_java3 小时前
Maven学习(一)
java·经验分享·笔记·学习·maven
sibylyue3 小时前
Nginx\Tomcat\Jetty\Netty
java·nginx·http
于先生吖3 小时前
基于 SpringBoot 架构,高性能 JAVA 动漫短剧系统源码
java·开发语言·spring boot
样例过了就是过了3 小时前
LeetCode热题100 跳跃游戏
c++·算法·leetcode·贪心算法·动态规划
无限进步_3 小时前
【C++&string】寻找字符串中第一个唯一字符:两种经典解法详解
开发语言·c++·git·算法·github·哈希算法·visual studio
斌味代码3 小时前
SpringBoot 3 实战:虚拟线程、全局异常处理与 JWT 鉴权完整方案
java·spring boot·后端
FluxMelodySun3 小时前
机器学习(二十九) 稀疏表示与字典学习(LASSO算法、KSVD算法、奇异值分解)
人工智能·算法·机器学习