题目描述

给定一个整数数组 temperatures ,表示每天的温度,返回一个数组 answer ,其中 answer[i] 是指对于第 i 天,下一个更高温度出现在几天后。如果气温在这之后都不会升高,请在该位置用 0 来代替。

示例 1:

1
2
输入: temperatures = [73,74,75,71,69,72,76,73]
输出: [1,1,4,2,1,1,0,0]

示例 2:

1
2
输入: temperatures = [30,40,50,60]
输出: [1,1,1,0]

示例 3:

1
2
输入: temperatures = [30,60,90]
输出: [1,1,0]

提示:

  • 1 <= temperatures.length <= 10^5
  • 30 <= temperatures[i] <= 100

解法

  • 单调栈
    • 维护递减栈,后入栈的元素总比栈顶元素小。
      • 若当前元素 < 栈顶元素:入栈
      • 若当前元素 > 栈顶元素:弹出栈顶元素,记录两者下标差值即为所求天数,这里用栈记录的是 T 的下标。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public static int[] dailyTemperatures(int[] temperatures) {
Stack<Integer> stack=new Stack<>();
int[] ans=new int[temperatures.length];
for (int i = 0; i < temperatures.length; i++) {
int temp=temperatures[i];
while (!stack.isEmpty()&&temperatures[stack.peek()]<temp){
int preIndex=stack.pop();
ans[preIndex]=i-preIndex;
}
stack.push(i);
}
return ans;
}
}
  • 时间复杂度:O(n)

来源:力扣(LeetCode)
链接:739. 每日温度 - 力扣(LeetCode)