LeetCode739 每日温度(Daily temperatures)

题目

Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the iᵗʰ day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead.

 Example 1: 
 Input: temperatures = [73,74,75,71,69,72,76,73]
Output: [1,1,4,2,1,1,0,0]
 Example 2: 
 Input: temperatures = [30,40,50,60]
Output: [1,1,1,0]
 Example 3: 
 Input: temperatures = [30,60,90]
Output: [1,1,0]

 Constraints: 
 1 <= temperatures.length <= 10 
 30 <= temperatures[i] <= 100 

方法

单调栈法

遍历数组的数字,将没找到等待时间的数字存入栈中(没找到等待时间意味着截止到遍历的当前数,还没有比它大的数),若遇到比栈中元素大的值(从栈顶开始比较)则记录等待时间并从栈中取出,在栈中未找到等待时间的数字默认等待时间为0

  • 时间复杂度:O(n),n为数组的长度
  • 空间复杂度:O(n),最坏情况下所有数字都要进栈
class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        int length = temperatures.length;
        Deque<Integer> stack = new LinkedList<>();
        int[] result = new int[length];
        for(int i=0;i<length;i++){
            int temperature = temperatures[i];
            while(!stack.isEmpty()&&temperature>temperatures[stack.peek()]){
                int preIndex = stack.pop();
                result[preIndex] =  i - preIndex;
            }
            stack.push(i);
        }
        return result;
    }
}
posted @   你也要来一颗长颈鹿吗  阅读(34)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示