739. Daily Temperatures
- 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