方法一:从后往前
class Solution:
def dailyTemperatures(self, T: List[int]) -> List[int]:
Next = [float('inf')]*102
ans = [0] * len(T)
for i in range(len(T)-1, -1, -1):
warmer = min(Next[t] for t in range(T[i]+1, 102))
if warmer < float('inf'):
ans[i] = warmer - i
Next[T[i]] = i
return ans
方法二:栈
class Solution:
def dailyTemperatures(self, T: List[int]) -> List[int]:
ans = [0] * len(T)
stack = []
for i in range(len(T)-1, -1, -1):
while stack and T[i] >= T[stack[-1]]:
stack.pop()
if stack:
ans[i] = stack[-1] - i
stack.append(i)
return ans
方法三:栈(正向)
class Solution:
def dailyTemperatures(self, T: List[int]) -> List[int]:
class Node:
def __init__(self, t, index):
self.t = t
self.index = index
stack = []
ans = [0] * len(T)
for i in range(len(T)):
while stack and T[i] > stack[-1].t:
top = stack.pop(-1)
ans[top.index] = i - top.index
node = Node(T[i], i)
stack.append(node)
while stack:
top = stack.pop(-1)
ans[top.index] = 0
return ans