从前向后遍历,用数组记录到当前位置之前最大的高度,从后向前记录最大的bar,两者中的小数-bar高度就是当前bar的存水量
class Solution(object):
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
if len(height) == 0 or len(height) == 1 or len(height) == 2:
return 0
leftbar = [0 for i in range(len(height))]
rightbar = height[-1]
max_left = height[0]
for i in range(len(height)):
leftbar[i] = max(max_left,height[i])
max_left = leftbar[i]
sum_water = 0
for i in range(len(height)-1,-1,-1):
rightbar = max(rightbar,height[i])
sum_water += min(leftbar[i],rightbar) - height[i]
return sum_water
C++中 stack.peek()和stack.pop()都返回栈顶元素,区别在于前者不改变栈,后者删除了栈顶元素
思路如果栈为空或者当前bar长度小于栈顶所存坐标的长度时,将坐标加入栈
否则,当栈不为空,而且当前bar长度大于栈顶元素所存坐标长度时,栈pop()min(当前bar长度,此时栈顶元素)-pop出的长度作为容器高度,当前bar的坐标-栈顶元素坐标-1,作为宽度,乘积计算此时的盛水量。循环此过程,直到不满足条件
当前坐标进栈
class Solution(object):
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
stack = []
sum_water = 0
for i in range(len(height)):
if len(stack) == 0 or height[i] < height[stack[-1]]:
stack.append(i)
else:
while len(stack) > 0 and height[i] > height[stack[-1]]:
pre = stack.pop()
if len(stack) >0:
sum_water += (min(height[i],height[stack[-1]]) - height[pre]) * (i-stack[-1]-1)
stack.append(i)
return sum_water