python 每日温度
生活随笔
收集整理的這篇文章主要介紹了
python 每日温度
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
| 每日溫度
請根據每日 氣溫 列表 temperatures ,請計算在每一天需要等幾天才會有更高的溫度。如果氣溫在這之后都不會升高,請在該位置用 0 來代替。示例 1:輸入: temperatures = [73,74,75,71,69,72,76,73] 輸出: [1,1,4,2,1,1,0,0] 示例 2:輸入: temperatures = [30,40,50,60] 輸出: [1,1,1,0] 示例 3:輸入: temperatures = [30,60,90] 輸出: [1,1,0]單調棧題解法
python code
class Solution:def dailyTemperatures(self, temperatures: List[int]) -> List[int]:length = len(temperatures)stack = list()result = [0] * lengthfor i, v in enumerate(temperatures):# 如果是空棧 后者當前元素小于棧頂元素 直接入棧if not stack or stack[-1][1] > v:stack.append((i, v))else:# 如果棧頂元素大于當前元素 棧頂元素出棧 繼續跟下一個棧頂元素對比while True:if stack and stack[-1][1] < v:# 通過索引相減 得到升溫之間間隔的天數num = i - stack[-1][0]index = stack.pop()[0]result[index] = numelse:# 把棧中比當前元素小的值全部彈出 最后在把當前元素入棧stack.append((i, v))breakreturn result總結
以上是生活随笔為你收集整理的python 每日温度的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python 栈的压入弹出序列
- 下一篇: python 接雨水