思路數組
# 用來保存結果集 res = [0] * len(T) # 臨時的stack tmp = [] # 遍歷數組T for index , t in enumerate(T): # 當 tmp不爲空,也就是以前還有沒有求出等待天數的溫度,並且當前的溫度大於以前的,沒有求出結果的最後一個溫度,(當前的溫度大於以前最後一個沒有求出結果的溫度,說明當前的溫度的下標減去以前溫度的下標就是以前溫度要等待的天數)開始while循環 while tmp and t > T[tmp[-1]]: # 把求出的天數保存到結果集對應的位置 res[tmp.pop()] = index - tmp[-1] # 把當前的下標保存到stack中 tmp.append(index) # 返回結果集 return res
class Solution: def dailyTemperatures(self, T: List[int]) -> List[int]: res = [0] * len(T) tmp = [] for index , t in enumerate(T): while tmp and t > T[tmp[-1]]: res[tmp.pop()] = index - tmp[-1] tmp.append(index) return res