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

相关推荐
huohaiyu13 分钟前
synchronized (Java)
java·开发语言·安全·synchronized
梵得儿SHI14 分钟前
Java 工具类详解:Arrays、Collections、Objects 一篇通关
java·工具类·collections·arrays·objects
兮山与18 分钟前
算法3.0
算法
熊小猿21 分钟前
Spring Boot 的 7 大核心优势
java·spring boot·后端
摸鱼的老谭23 分钟前
Java学习之旅第二季-13:方法重写
java·学习·方法重写
云灬沙23 分钟前
IDEA2025无法更新使用Terminal控制台
java·intellij-idea·idea·intellij idea
Yield & Allure24 分钟前
IDEA在plugins里搜不到mybatisx插件的解决方法
java·ide·intellij-idea
yunmi_28 分钟前
安全框架 SpringSecurity 入门(超详细,IDEA2024)
java·spring boot·spring·junit·maven·mybatis·spring security
孤独斗士29 分钟前
解决Intellij IDEA控制台,logger.info(),system.out.println()等中文乱码问题
java·ide·intellij-idea
shepherd11133 分钟前
JDK 8钉子户进阶指南:十年坚守,终迎Java 21升级盛宴!
java·后端·面试