解题思路
使用单调栈(单调递减栈)来存储数组下标,栈中的下标对应的温度是递减的(从栈底到栈顶)
- 当前遍历的温度如果大于栈顶温度,说明找到了距离栈顶温度最近的下一个更高温度,此时就可以计算出距离栈顶温度最近的下一个更高温度出现的天数,并将结果存储在结果数组中。
- 如果当前温度不大于栈顶温度,则将当前温度的索引入栈,继续遍历下一个温度,保持栈的单调递减性质。
参考代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| class Solution { public int[] dailyTemperatures(int[] temperatures) { int[] res = new int[temperatures.length]; Stack<Integer> stack = new Stack<>();
for(int i = 0; i < temperatures.length; i ++) { while(!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) { int index = stack.peek(); res[index] = i - index; stack.pop(); } stack.push(i); } return res; } }
|