Article Directory
Title description
Ideas
- Monotonic Stack-the subscripts of the array elements are stored in the stack
class Solution:
def dailyTemperatures(self, T: List[int]) -> List[int]:
stack = []
res = [0] * len(T)
for i in range(len(T)):
if not stack or T[i] <= T[stack[-1]]: # 栈空 或 T[i]小于栈顶元素
stack.append(i)
else:
while stack and T[i]>T[stack[-1]]:
top = stack.pop()
res[top] = i-top
stack.append(i)
return res
-
Complexity analysis
-
Time complexity: O (n) O(n)O ( n- ) , which
n
is the length of the temperature of the list. The temperature list is traversed in the forward direction. For each subscript in the temperature list, there is at most one push and pop operation. -
Space complexity: O (n) O(n)O ( n- ) , which
n
is the length of the temperature of the list. Need to maintain a monotonic stack to store the subscripts in the temperature list.