0%

Daily Temperatures

Question

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].

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/*
@param: int[]
@return: int[]
Algorithm: 单调栈
*/
public int[] dailyTemperatures(int[] T) {
Stack<Integer> stack = new Stack<>();

int i = 0;
int[] res = new int[T.length];
while (i < T.length) {
while (!stack.isEmpty() && T[i] > T[stack.peek()]) {
int temp = stack.pop();
res[temp] = i - temp;
}
stack.push(i);
i++;
}
return res;
}