739. Daily Temperatures

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
int[] res = new int[temperatures.length];

Stack<Integer> decreaseStack = new Stack<>(); // 非严格单调递减栈,栈中存储的为天的索引
for (int i = 0; i < temperatures.length; i++) {
while (!decreaseStack.isEmpty() && temperatures[i] > temperatures[decreaseStack.peek()]) {
// 出现了更高的温度,此时记录
int prevIndex = decreaseStack.pop();
res[prevIndex] = i - prevIndex;
}

decreaseStack.push(i);
}

return res;
}
}

References

739. Daily Temperatures
剑指 Offer II 038. 每日温度