Given a list of daily temperatures ( \text{temperatures} ), 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.
Monotonic Stack
answer
of the same length as temperatures
, initialized with zeros.answer
list at that index with the difference between the current index and the popped index.class Solution(object):
def dailyTemperatures(self, temperatures):
"""
:type temperatures: List[int]
:rtype: List[int]
"""
n = len(temperatures)
answer = [0] * n
stack = []
for i in range(n):
while stack and temperatures[i] > temperatures[stack[-1]]:
idx = stack.pop()
answer[idx] = i - idx
stack.append(i)
return answer