【LeetCode】739. 每日温度

问题描述

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].

给定一个日温度T的列表,返回一个这样的列表,对于输入的每一天,它告诉您需要等待多少天直到温度升高。如果未来没有任何一天这是可能的,代之以0。
例如,给定温度T =[73, 74, 75, 71, 69, 72, 76, 73],输出应该是[1,1,4,2,1,1,0,0]。
注:温度的长度将在[1,30000]范围内。每个温度都是[30,100]范围内的整数。

Python 实现

使用栈:根据问题的描述,最后返回的结果实际上是目标值下标的差值,因此我们需要存储起来进行比较观察的值是每个值的下标。此外可以假想一下,当后一个值比前一个小时,我们需要把后一个值存储起来继续讨论;当后一个值比前一个值大时,前一个值我们将不再讨论,同样把后一个值存起来继续后面的讨论。因此这个过程可以用栈来实现,将下标存入栈中,用以计算结果所需要的差值。

class Solution(object):
    def dailyTemperatures(self, T):
        """
        :type T: List[int]
        :rtype: List[int]
        """ 
        
        if T == None or len(T) == 0:
            return []
        
        # Stack: greater then pop; smaller then append.
        stack = []
        ret = [0] * len(T)
        
        for i in range(len(T)):
            while len(stack) > 0 and T[i] > T[stack[-1]]:
                ret[stack[-1]] = i - stack[-1]
                stack.pop(-1)
                
            # Save indeces in the stack.
            stack.append(i)
            
        return ret
        

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

发布了45 篇原创文章 · 获赞 29 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/sinat_36645384/article/details/103971141