题目描述:
根据每日 气温 列表,请重新生成一个列表,对应位置的输出是需要再等待多久温度才会升高超过该日的天数。如果之后都不会升高,请在该位置用 0 来代替。
示例:
给定一个列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73],你的输出应该是 [1, 1, 4, 2, 1, 1, 0, 0]。 提示:气温 列表长度的范围是 [1, 30000]。每个气温的值的均为华氏度,都是在 [30, 100] 范围内的整数。
解答代码:
class Solution {public int[] dailyTemperatures(int[] T) {LinkedList<Integer> stack = new LinkedList<Integer>();int[] result = new int[T.length];for (int i = 0; i < T.length; i++) {while (!stack.isEmpty() && T[i] > T[stack.peek()]) {result[stack.peek()] = i - stack.pop();}stack.push(i);}return result;}}
解答思路:
单调栈。
遍历数组,若栈为空或当日温度小于等于栈顶温度,入栈。
反之,while循环把能出栈的元素取出来,再入栈。
注意计算的是差的天数而不是温度。
