在一个数组里找到后一个比前一个温度高的index差距, 问题问的是index差距, 所以stack里面不能存温度
Monotonic stacks are a good option when a problem involves comparing the size of numeric elements, with their order being relevant.
stack被用来比较数据大小, 尤其是顺序很相关的时候
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
int n = temperatures.length;
int[] result = new int[n];
Stack<Integer> stack = new Stack<>();
stack.push(0);
for (int i = 1; i < n; i++){
// 注意要考虑stack是不是empty 比较温度大小不一定要用if-else (当可以用while的时候)
while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]){
int tmp = stack.pop();
result[tmp] = i - tmp;
}
stack.push(i);
}
return result;
}
}