这个题一开始想麻烦了,我用单调栈实现了一下,A了,但是只打败了0.4%的人,后来看了一眼别人的博客,发现没那么麻烦,找到最高点,从左右贪心就行了。。。
下面是两份不同做法的代码,时间复杂度都是O(n)
class Solution(object):
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
Len=len(height)
if Len<=1:return 0
ans=0
MAX=0
p=0
for i in range(0,Len):
if height[i]>MAX:
MAX=height[i]
p=i
cur=height[0]
for i in range(1,p):
if cur<height[i]:
cur=height[i]
else:
ans+=cur-height[i]
cur=height[Len-1]
for i in range(Len-2,p,-1):
if cur<height[i]:
cur=height[i]
else:
ans+=cur-height[i]
return ans
class Solution(object):
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
Len=len(height)
if Len<=1:return 0
stack=[]
stack.append((height[0],0))
ans=0
#print "len",Len
for i in range(1,Len):
print i
stackSize=len(stack)
if height[i]<stack[stackSize-1][0]:
#print"fuck1"
stack.append((height[i],i))
print stack
elif height[i]==stack[stackSize-1][0]:
#print "fuck2"
stack.pop()
stack.append((height[i],i))
else:
#print"fuck"
hereH=height[i]
V=0
lowest=stack.pop()
V+=lowest[0]
stackSize-=1
while(stackSize>0 and stack[stackSize-1]<=lowest[0]):
lowest=stack.pop()
V+=lowest[0]
stackSize-=1
higher=(-1,-1)
V-=lowest[0]
while stackSize>0 and stack[stackSize-1]>=lowest[0]:
higher=stack.pop()
V+=lowest[0]*(lowest[1]-higher[1])
#print "V",V
stackSize-=1
if higher[0]>=hereH:
stack.append(higher)
break
lowest=higher
if higher[0]!=-1:
ans+=min(higher[0],hereH)*(i-higher[1]-1)-V
#print "ans",ans,V
if higher[0]==hereH:
stack.pop()
stack.append((hereH,i))
return ans