classSolution(object):deftrap(self, height):"""
:type height: List[int]
:rtype: int
"""# 动态规划/双指针/图解
maxleft =[0]*len(height)
maxright =[0]*len(height)
maxleft[0]= height[0]
maxright[len(height)-1]= height[-1]
res=0for i inrange(1,len(height)):
maxleft[i]=max(height[i],maxleft[i-1])for i inrange(len(height)-2,-1,-1):
maxright[i]=max(height[i],maxright[i+1])for i inrange(len(height)):
res +=min(maxleft[i],maxright[i])-height[i]return res
二、单调栈
classSolution(object):deftrap(self, height):"""
:type height: List[int]
:rtype: int
"""# 单调栈
res=0
stack=[0]for i inrange(1,len(height)):whilelen(stack)!=0and height[stack[-1]]< height[i]:
mid = stack.pop()if stack:
h =min(height[stack[-1]],height[i])-height[mid]
w = i - stack[-1]-1
res += h*w
stack.append(i)return res