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;
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理