LeetCode 739. Daily Temperatures解题报告(python)

739. Daily Temperatures

  1. Daily Temperaturesp ython solution

题目描述

Given a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead.
For example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0].
Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100].

解析

如果正序遍历数组,找到一个温度,记录下来该温度的位置,然后再向后查找,直到找到大于该温度的位置。将两个位置做差,存到相应的res[i]中。这么做时间复杂度有点高。
从右向左也就是逆序遍历数组会减少很多重复性的工作。从右向左,如果该位置的值是最大的,那么令res[i]=0,使用一个新的变量current_max来记录目前出现过的最大值。如果该位置的值小于current_max,那么就一定存在大于该位置温度的温度值。需要逐个向后查找,直到找到大于该位置的温度值。
在向后查找的过程中,又不需要每次都向后进一个,可以利用之前已经完成的res数组加速查找,加快跳转。

class Solution:
    def dailyTemperatures(self, T: List[int]) -> List[int]:
        n=len(T)
        current_max=0
        res=[0]*n
        for i in range(n-1,-1,-1):
            t=T[i]
            if current_max <=t:
                current_max=t
            else:
                temp=1
                while T[i+temp]<=t:
                    temp+=res[i+temp]
                res[i]=temp
        return res

Reference

https://leetcode.com/problems/daily-temperatures/discuss/397728/Easy-Python-O(n)-time-O(1)-space-beat-99.9

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值