739. 每日温度
单调栈的特点:
- 栈内递增或者递减
- 遇见不符合的数据是栈内数据第一次在右边遇见不满足趋势的数据
本题才用严格单调递减来做,所以栈内遇见不满足的数据,就是第一个会碰到的数据。
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
Stack<Integer> stack = new Stack<>();
int[] array = new int[temperatures.length];
for(int i=0; i<temperatures.length; i++) {
int num = temperatures[i];
while(!stack.isEmpty() && temperatures[stack.peek()] < num) {
array[stack.peek()] = i - stack.peek();
stack.pop();
}
stack.push(i);
}
return array;
}
}
网友评论