【Leetcode_总结】 739. 每日温度 - python

Q:

根据每日 气温 列表,请重新生成一个列表,对应位置的输入是你需要再等待多久温度才会升高的天数。如果之后都不会升高,请输入 0 来代替。

例如,给定一个列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73],你的输出应该是 [1, 1, 4, 2, 1, 1, 0, 0]

提示:气温 列表长度的范围是 [1, 30000]。每个气温的值的都是 [30, 100] 范围内的整数。


思路:使用堆栈保存还没遇到大于自己的数组元素的索引,遍历数组元素,跟栈顶元素比较,如果大于栈顶的元素,则保存栈顶元素的结果,并出栈。如果栈非空,继续跟栈顶的元素比较。

链接:https://leetcode-cn.com/problems/daily-temperatures/description/

代码:

class Solution(object):
    def dailyTemperatures(self, T):
        """
        :type T: List[int]
        :rtype: List[int]
        """
        tmp = []
        res = [0 for _ in range(len(T))]
        for i in range(len(T)):
            while len(tmp) != 0 and T[i] > T[tmp[-1]]:
                res[tmp[-1]] = i - tmp[-1]
                tmp.pop()
            tmp.append(i)
        return res

猜你喜欢

转载自blog.csdn.net/maka_uir/article/details/86599670