1. 程式人生 > >leetcode.每日溫度

leetcode.每日溫度

根據每日 氣溫 列表,請重新生成一個列表,對應位置的輸入是你需要再等待多久溫度才會升高的天數。如果之後都不會升高,請輸入 0 來代替。

例如,給定一個列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73],你的輸出應該是 [1, 1, 4, 2, 1, 1, 0, 0]。

提示:氣溫 列表長度的範圍是 [1, 30000]。每個氣溫的值的都是 [30, 100] 範圍內的整數。
方法一:
建立一個棧,棧頂儲存最小元素
可惜超時:

class Solution(object):
    def dailyTemperatures(self, T)
: """ :type T: List[int] :rtype: List[int] """ length = len(T) hightem = [0]*length for i in range(length): Flag = False j = i+1 stack = [] while j < length: if T[j] <=
T[i]: stack.append(T[j-1]) else: Flag = True stack.append(T[j-1]) break j+=1 if not Flag: stack = [] hightem[i] = len(stack) stack = [
] return hightem

方法二:
最小棧,儲存最小值的索引

class Solution(object):
    def dailyTemperatures(self, T):
        """
        :type T: List[int]
        :rtype: List[int]
        """
        
        stack = []#建立最小棧,棧中儲存數值索引
        t_length = len(T)
        res = [0 for i in range(t_length)]
        
        for key,value in enumerate(T):
            if stack:
                while stack and T[stack[-1]] < value:#如果當前值大於棧頂元素,對應位置的結果賦值為索引差值,就彈出棧頂元素,
                    res[stack[-1]] = key - stack[-1]
                    stack.pop()
            stack.append(key)#當前索引賦值棧
        return res