Skip to content

Latest commit

 

History

History
25 lines (22 loc) · 1.08 KB

73. 每日温度.md

File metadata and controls

25 lines (22 loc) · 1.08 KB

请根据每日气温列表,重新生成一个列表。对应位置的输出为:要想观测到更高的气温,至少需要等待的天数。如果气温在这之后都不会升高,请在该位置用 0 来代替。

例如,给定一个列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73],输出应该是 [1, 1, 4, 2, 1, 1, 0, 0]。
class Solution(object):
    def dailyTemperatures(self, temperatures):
        """
        :type temperatures: List[int]
        :rtype: List[int]
        """
        #思路:递减栈,遍历整个数组,如果栈不空,且当前数字大于栈顶元素,取出栈顶元素,直接求出下标差就是二者的距离,继续看新的栈顶元素,直到当前数字小于等于栈顶元素停止,然后将数字对应下标入栈,
        n = len(temperatures)
        res = [0]*n
        stack = []

        for i in range(n):
            while (stack and temperatures[i] > temperatures[stack[-1]]):
                ind = stack.pop()
                res[ind] = i - ind
            stack.append(i)
        return res