链接:739. 每日温度 - 力扣(LeetCode)

维护一个单调递减的栈,直到下一个数比栈尾大,就一直弹出,并记录两个下标差值。其他没有记录的默认为0

这个方法可以用于在 O(n) 的时间复杂度内求出数组中各个元素右侧第一个更大或更小的元素及其下标,然后一并得到其他信息。

 1 class Solution(object):
 2     def dailyTemperatures(self, temperatures):
 3         """
 4         :type temperatures: List[int]
 5         :rtype: List[int]
 6         """
 7         help_stack = []
 8         length = len(temperatures)
 9         res = [0] * length
10         i = 0
11         while i < length:
12             if not help_stack or temperatures[i] <= temperatures[help_stack[-1]]:
13                 help_stack.append(i)
14             else:
15                 while help_stack and temperatures[i] > temperatures[help_stack[-1]]:
16                     j = help_stack[-1]
17                     res[j] = i - j
18                     help_stack.pop()
19                 help_stack.append(i)
20             i += 1
21         return res