Given a list of daily temperatures
, produce
a list 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 temperatures = [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]
.
自己写的O(n方)的算法,超时了没AC
class Solution(object):
def dailyTemperatures(self, temperatures):
"""
:type temperatures: List[int]
:rtype: List[int]
"""
result=[]
for i in range (0,len(temperatures)-1):
for j in range(i+1,len(temperatures)):
if (temperatures[i]<temperatures[j]):
print("current j is",j,"i is",i,"j-i is",j-i)
result.append(j-i)
break
if j == len(temperatures)-1:
result.append(0)
result.append(0)#最后一个温度,因为是最后一个,所以不会有比它更高的温度
return result
这道题的标签是HashMap,于是我看下别人咋写的
class Solution(object):
def dailyTemperatures(self, T):
"""
:type temperatures: List[int]
:rtype: List[int]
"""
ans = [0] * len(T)
stack = [] #indexes from hottest to coldest
for i in xrange(len(T) - 1, -1, -1):#改成range也能AC
while stack and T[i] >= T[stack[-1]]:
stack.pop()
if stack:
ans[i] = stack[-1] - i
stack.append(i)
return ans
Amazing!
为了方便理解可以看下面:
T = [73, 74, 75, 71, 69, 72, 76, 73]
ans = [0] * len(T)
stack = [] #indexes from hottest to coldest
for i in range(len(T) - 1, -1, -1):
print("i is ",i)
while stack and T[i] >= T[stack[-1]]:
stack.pop()
print("stack after pop is", stack)
if stack:
ans[i] = stack[-1] - i
print("stack[-1] is",stack[-1],"so ans[i] is ",ans[i] )
stack.append(i)
print("stack after append is ",stack)
print("result is ",ans)
运行结果是
i is 7
stack after append is [7]
i is 6
stack after pop is []
stack after append is [6]
i is 5
stack[-1] is 6 so ans[i] is 1
stack after append is [6, 5]
i is 4
stack[-1] is 5 so ans[i] is 1
stack after append is [6, 5, 4]
i is 3
stack after pop is [6, 5]
stack[-1] is 5 so ans[i] is 2
stack after append is [6, 5, 3]
i is 2
stack after pop is [6, 5]
stack after pop is [6]
stack[-1] is 6 so ans[i] is 4
stack after append is [6, 2]
i is 1
stack[-1] is 2 so ans[i] is 1
stack after append is [6, 2, 1]
i is 0
stack[-1] is 1 so ans[i] is 1
stack after append is [6, 2, 1, 0]
result is [1, 1, 4, 2, 1, 1, 0, 0]