题目
给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1]
表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。
示例:
输入: [0,1,0,2,1,0,1,3,2,1,2,1]
输出: 6
方案一
class Solution:
def trap(self, height: List[int]) -> int:
if not height:
return 0
# 遍历一次找到最高的柱子的高度
_max = max(height)
res = 0
# 从前往后遍历
p1 = 0 # 前一个低的柱子的高度,上图中 index = 1, 3, 7
for i in range(len(height)):
if height[i] == _max:
break
if p1 == 0 or height[i] >= p1:
p1 = height[i]
continue
res = res + p1 - height[i]
# 从后往前遍历
p2 = 0
for j in range(len(height) - 1, -1, -1):
if height[j] == _max:
break
if p2 == 0 or height[j] >= p2:
p2 = height[j]
continue
res = res + p2 - height[j]
# 有多个最高点
if i != j:
for k in range(i + 1, j):
res = res + _max - height[k]
return res
class Solution:
def trap(self, height: List[int]) -> int:
if not height:
return 0
n=len(height)
left,right=0,n-1
ans=0
maxleft=height[0]
maxright=height[n-1]
while left<right:
maxleft=max(maxleft,height[left])
maxright=max(maxright,height[right])
if maxleft<maxright:
ans+=maxleft-height[left]
left+=1
else:
ans+=maxright-height[right]
right-=1
return ans