Original link: https://leetcode.com/problems/daily-temperatures/
Given a list of daily temperatures, return a list such that tell how many days you would have to wait until a warmer temperature.
Initialize a stack (list) to store position.
Iterate the array T in the reverse sequence, the stack will pop out position where the temperature (T[stack[-1]) is less than the current temperature (T[i]).
The remained last element in stack is the position where the temperature is larger than the current one. If the stack is empty, it means that elements after the current one are all smaller.
Code:
class Solution:
def dailyTemperatures(self, T: List[int]) -> List[int]:
ans = [0 for i in range(len(T))]
stack = []
for i in range(len(T)-1, -1, -1):
while stack and T[stack[-1]] <= T[i]:
stack.pop()
if stack:
ans[i] = stack[-1] - i
stack.append(i)
return ans