Given a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead.

For example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0].

Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100].

分析:

为了找到后面过了几天会有比当前值更大的值,所以,我们需要从尾遍历,我们用一个stack来存当前最大值。

 public class Solution {
public int[] dailyTemperatures(int[] T) {
if (T == null) return null;
int[] result = new int[T.length];
Stack<Temperature> stack = new Stack<>(); for (int i = T.length - ; i >= ; i--) {
if (stack.isEmpty()) {
result[i] = ;
stack.push(new Temperature(T[i], i));
} else if (stack.peek().value > T[i]) {
result[i] = stack.peek().index - i;
stack.push(new Temperature(T[i], i));
} else {
while (!stack.isEmpty() && stack.peek().value <= T[i]) {
stack.pop();
}
if (stack.isEmpty()) {
result[i] = ;
} else {
result[i] = stack.peek().index - i;
}
stack.push(new Temperature(T[i], i));
}
}
return result;
}
} class Temperature {
int value;
int index; public Temperature(int value, int index) {
this.value = value;
this.index = index;
}
}
05-28 16:00