[739. 每日温度]
难度 中等
根据每日 气温
列表,请重新生成一个列表,对应位置的输出是需要再等待多久温度才会升高超过该日的天数。如果之后都不会升高,请在该位置用 0
来代替。
例如,给定一个列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73]
,你的输出应该是 [1, 1, 4, 2, 1, 1, 0, 0]
。
提示:气温
列表长度的范围是 [1, 30000]
。每个气温的值的均为华氏度,都是在 [30, 100]
范
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/daily-temperatures
解法:单调栈
可以使用单调栈 stack 来解决这个问题,栈内存储的是对应温度在数组中下标,。
对于 temperatures 中的第 i 个元素
- 如果 temperatures [i] <= 栈顶元素(即当前温度 <= 栈顶元素所表示的温度),直接将 i 入栈
- 如果 temperatures [i] > 栈顶元素(即当前温度 > 栈顶元素所表示的温度)
栈顶元素出栈(记作 index),则 ans[index] = i - index,重复该操作直到栈为空 或者 temperatures [i] <= 栈顶元素
class Solution {
public int[] dailyTemperatures(int[] T) {
int len = T.length;
int[] ans = new int[len];
if(T == null || T.length == 0) {
return ans;
}
Stack<Integer> stack = new Stack();
stack.push(0);
for(int i = 1; i < len; i++) {
while(!stack.isEmpty() && T[i] > T[stack.peek()]) {
ans[stack.peek()] = i - stack.peek();
stack.pop();
}
stack.push(i);
}
//对
//因为数组的元素默认为 0 ,这段代码可以省略
while(!stack.isEmpty()) {
ans[stack.peek()] = 0;
stack.pop();
}
return ans;
}
}