Daily Temperatures
stack
, monotonous stack
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, put0
instead.
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 oftemperatures
will be in the range[1, 30000]
. Each temperature will be an integer in the range[30, 100]
.
Analysis
Brute-force
Brute-force的方法就略去不表,时间复杂度O(n^2)。
Stack
Brute-force有很多是重复搜索,更有效率的是利用Stack,一个单调递增的stack。逆序的方式进行扫描。
举例:
T = [73, 74, 75, 71, 69, 72, 76, 73]
如下:
对于结果来说:
ans[i] = stack.isEmpty() ? 0 : stack.peek() - i;
注意:
T[i] >= T[stack.peek()]
时候要不断pop()
,然后再放入当前下标i。这里要允许"="
的条件,因为需要寻找第一个出现的位置,因此重复位置要pop()
出来。
这一题用Stack很妙,十分经典。As @FrancisGee points out:
When I saw the question in this competition, I firstly think about Monotonous stack 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()
Brute-force O(n^2) - (348 ms)
Reference
https://leetcode.com/problems/daily-temperatures/solution/
https://leetcode.com/problems/daily-temperatures/discuss/109832/Java-Easy-AC-Solution-with-Stack
Last updated