首页 > 其他 > 详细

leetcode-739. 每日温度

时间:2018-08-19 22:56:32      阅读:166      评论:0      收藏:0      [点我收藏+]

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

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

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

 

思路:

  1. 暴力(超时)。

  2. 维护一个后一天的气温不比前一天的气温高的栈,这个栈对应的温度是递减的。每遍历到一个元素与栈中的元素做对比,做相应处理即可(这里我在栈中维护的是对应天气的索引)。

 

代码:

class Solution:
    def dailyTemperatures(self, temperatures):
        """
        :type temperatures: List[int]
        :rtype: List[int]
        """

        stack = []
        res = [0 for _ in temperatures]
        for i in range(len(temperatures) - 1):
            if temperatures[i] < temperatures[i + 1]:
                res[i] = 1
                while len(stack) != 0 and temperatures[i + 1] > temperatures[stack[len(stack) - 1]]:
                    res[stack[len(stack) - 1]] = i + 1 - stack[len(stack) - 1]
                    stack.pop()
            else:
                stack.append(i)

        return res

if __name__ == __main__:
    s = Solution()
    print(s.dailyTemperatures([73, 74, 75, 71, 69, 72, 76, 73]))

 

leetcode-739. 每日温度

原文:https://www.cnblogs.com/namedlxd/p/9503110.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!