请根据每日 气温 列表,重新生成一个列表。对应位置的输出为:要想观测到更高的气温,至少需要等待的天数。如果气温在这之后都不会升高,请在该位置用 0 来代替。
例如,给定一个列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73],你的输出应该是 [1, 1, 4, 2, 1, 1, 0, 0]。
提示:气温 列表长度的范围是 [1, 30000]。每个气温的值的均为华氏度,都是在 [30, 100] 范围内的整数。(第一个和第二个我写的,任何人是有差距的,不管你信不信)
链接:https://leetcode-cn.com/problems/daily-temperatures/solution/mei-ri-wen-du-by-leetcode-solution/
class Solution(object):
def dailyTemperatures1(self, T):
"""
:type T: List[int]
:rtype: List[int]
"""
stack = []
output = []
while T:
if not stack:
stack.append(T.pop())
output.append(0)
continue
count = 0
flag = False
len_stack = len(stack) - 1
while stack and len_stack >= 0:
if stack[len_stack] <= T[-1]:
count += 1
else:
flag = True
count += 1
break
len_stack -= 1
if not flag:
count = 0
output.append(count)
stack.append(T.pop())
return output[::-1]
def dailyTemperatures2(self, T):
"""
:type T: List[int]
:rtype: List[int]
"""
ret_len = len(T)
temp_dict = {}
ret_list = [0 for _ in range(ret_len)]
inf = float("inf")
for i in range(ret_len-1, -1, -1):
min_index = inf
for item in temp_dict:
if item > T[i]:
temp_index = temp_dict.get(item, inf)
min_index = min(temp_index, min_index)
if min_index != inf:
ret_list[i] = min_index - i
temp_dict[T[i]] = i
return ret_list
def dailyTemperatures3(self, T):
"""单调递增栈 https://www.jianshu.com/p/6bbd3653a57f
:type T: List[int]
:rtype: List[int]
"""
ret_len = len(T)
ret_list = [0 for _ in range(ret_len)]
stack = []
for i in range(ret_len-1, -1, -1):
if not stack:
stack.append((i, T[i]))
else:
while stack and stack[-1][1] <= T[i]:
stack.pop()
if stack:
ret_list[i] = stack[-1][0] - i
stack.append((i, T[i]))
return ret_list
def dailyTemperatures(self, T):
"""KMP失陪数组"""
n = len(T)
ans = [0] * n
for i in range(n-2, -1, -1):
now = i+1
while T[now] <= T[i]:
if ans[now]:
now += ans[now]
else:
break
else:
ans[i] = now-i
return ans
if __name__ == '__main__':
temperatures = [55, 38, 53, 81, 61, 93, 97, 32, 43, 78]
s1 = Solution()
root = s1.dailyTemperatures(temperatures)
print(root