Daily Temperatures
Question
Given a list of daily temperatures, produce a list 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 temperatures = [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].
Solution
自己參加 contest 的時候寫不出來,用了一個很 naive 的方式但得到了 TLE。看了解答之後發現,題目要求的是第一個比自己大的數在哪裡,因此可以套用 Largest Rectangle in Histogram 的方法,用一個 “遞減 stack”(概念跟遞增 stack 相同) 來達到此目的。
具體概念是說,我們只要遇到比 temperatures[stack.peek()] 小的數,就存進 stack 裡面,當遇到比較大的數,就 stack.pop 並用兩個 index 相減,就可以得到相差的天數
public int[] dailyTemperatures(int[] temperatures) {
if (temperatures == null || temperatures.length == 0) {
return null;
}
int len = temperatures.length;
int[] result = new int[len];
Stack<Integer> stack = new Stack<Integer>();
for (int i = 0; i < len; i++) {
while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) {
int index = stack.pop();
result[index] = i - index;
}
stack.push(i);
}
return result;
}