LeetCode:739. Daily Temperatures
Given a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead.
For example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0].
Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100].
给定一组温度值列表,对于每个位置 i ,求出比该位置温度高的最近的下一个位置。
思路一:暴力求解
从后向前遍历,用两个哨兵分别指向最低温度位置和最高温度位置。
- 如果当前温度小于最低温度则表示后面的所有温度都大于当前温度,只要 1 天就可以达到更暖的温度。
- 如果当前温度大于最大温度,则需要的天数为0。
- 而在最低温度和最高温度之间的温度,则需要遍历后面的所有温度找到最近的更暖温度位置。
这种解法思路正确但是不能AC。参考一下即可:
Python 代码实现
class Solution:
def dailyTemperatures(self, T: List[int]) -> List[int]:
l = len(T)
res = [0]*l
minPos = l-1
maxPos = l-1
for i in range(l-2, -1, -1):
if (T[i] < T[minPos]):
res[i] = 1
minPos = i
elif (T[i] > T[maxPos]):
res[i] = 0
maxPos = i
else:
for j in range(i,l):
if(T[j] > T[i]):
res[i] = j-i
break
return res
如果整个列表很长的时候,每次遍历后面所有天数花费时间较长。优化一下上面这个方法,考虑采用哈希的方法保存每个温度所在位置,这样在某个位置的时候,只要遍历当前位置的温度值到100度之间的所有温度,找到第一个大于该温度且位置不为-1的位置,然后更新当前温度的位置即可。
class Solution:
def dailyTemperatures(self, T: List[int]) -> List[int]:
l = len(T)
res = [0]*l
# 保存每个温度值出现的最靠前的位置
tPos = [-1]*101
for i in range(l-1, -1, -1):
# 从当前温度开始遍历到100度
for j in range(T[i],101):
# 如果发现某个温度的出现位置不为-1,并且温度大于当前位置
if(tPos[j] >= 0 and j > T[i]):
# 天数为0或者天数小于当前值,则更新
if (res[i] ==0 or res[i] > (tPos[j]-i)):
res[i] = tPos[j]-i
# 更新位置
tPos[T[i]] = i
return res
思路二:栈
还是从后向前遍历,这里使用栈来保存当前温度值到最大温度值的一个升序列表区间(栈顶最小),如果发现当前位置温度大于栈顶温度则一直弹出栈顶,如果当前位置温度小于栈顶则直接入栈。
class Solution(object):
def dailyTemperatures(self, T):
ans = [0] * len(T)
stack = [] #indexes from hottest to coldest
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
以 T = [73, 74, 75, 71, 69, 72, 76, 73] 为例:
- 首先访问73的时候,栈空,直接入栈,栈为[73];
- 访问76,76>73,弹出栈顶元素73,并将76入栈,栈为[76];
- 访问72,72小于栈顶元素76,所以72对应的最小天数为1,并将72入栈,栈为[72,76];
- 访问69,69小于栈顶元素72,所以69对应的最小天数为1,并将69入栈,栈为[69,72,76];
- 依次类推,得到最终解。
THE END.