请根据每日 气温 列表 temperatures ,请计算在每一天需要等几天才会有更高的温度。如果气温在这之后都不会升高,请在该位置用 0 来代替。
示例 1:
输入: temperatures = [73,74,75,71,69,72,76,73]
输出: [1,1,4,2,1,1,0,0]
示例 2:
输入: temperatures = [30,40,50,60]
输出: [1,1,1,0]
示例 3:
输入: temperatures = [30,60,90]
输出: [1,1,0]
提示:
1 <= temperatures.length <= 105
30 <= temperatures[i] <= 100
class Solution {
/**
本题采用单调栈解决,具体的使用单调递减栈,因为我们是遇到第一个比栈顶元素大的值就出栈,我们栈里面存储下标值
*/
public int[] dailyTemperatures(int[] temperatures) {
int n = temperatures.length;
Deque<Integer> stack = new LinkedList<>();
int[] res = new int[n];
for (int i = 0; i < n; ++i) {
while (!stack.isEmpty() && temperatures[stack.peek()] < temperatures[i]) {
int idx = stack.poll();
res[idx] = i - idx;
}
stack.push(i);
}
return res;
}
}
数组模拟
class Solution {
int[] st;
int tt;
public int[] dailyTemperatures(int[] temperatures) {
int n = temperatures.length;
int[] res = new int[n];
st = new int[n + 1];
for (int i = 0; i < n; ++i) {
while (tt > 0 && temperatures[st[tt]] < temperatures[i]) {
int tem = st[tt--];
res[tem] = i - tem;
}
st[++tt] = i;
}
return res;
}
}