Given a list of daily temperaturesT, 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, put0instead.
For example, given the list of temperaturesT = [73, 74, 75, 71, 69, 72, 76, 73], your output should be[1, 1, 4, 2, 1, 1, 0, 0].
Note:The length oftemperatureswill be in the range[1, 30000]. Each temperature will be an integer in the range[30, 100].
When I saw the question in this competition, I firstly think about Monotonousstack inspired by Largest Rectangle in Histogram. Because Monotonous stack can help us find first largest element in O(n) time complexity.
这种单调栈的思想需要多加琢磨咀嚼。
Time Complexity - O(n)
Space Complexity - O(n)
Solution
Stack with reverse order iteration T.length - 1 to 0 - Time: O(n), Space: O(n) - (52 ms)
Stack with 0 to T.length - 1 order iteration (17 ms, faster than 92.98%)
Using ArrayDeque() will significantly increase performance than Stack()
class Solution {
public int[] dailyTemperatures(int[] T) {
int[] ans = new int[T.length];
Deque<Integer> stack = new ArrayDeque<>();
for (int i = T.length - 1; i >= 0; i--) {
while (!stack.isEmpty() && T[i] >= T[stack.peek()]) {
stack.pop();
}
ans[i] = stack.isEmpty() ? 0 : stack.peek() - i;
stack.push(i);
}
return ans;
}
}
class Solution {
public int[] dailyTemperatures(int[] T) {
Deque <Integer> stack = new ArrayDeque<>();
int[] ret = new int[T.length];
for (int i = 0; i < T.length; i++) {
while (!stack.isEmpty() && T[i] > T[stack.peek()]) {
int idx = stack.pop();
ret[idx] = i - idx;
}
stack.push(i);
}
return ret;
}
}
class Solution {
public int[] dailyTemperatures(int[] T) {
int n = T.length;
int[] ans = new int[n];
int days = 0;
for (int i = 0; i < n; i++) {
days = 0;
for (int j = i; j < n; j++) {
if (T[j] > T[i]) {
ans[i] = days;
break;
} else {
days++;
}
}
}
return ans;
}
}