以列表的形式给定
n
n
n个非负整数表示每个宽度为
1
1
1的柱子的高度图,列表的索引表示对应柱子左边界所处坐标。计算按此排列的柱子,下雨之后能接多少雨水。如:
[
0
,
1
,
0
,
2
,
1
,
0
,
1
,
3
,
2
,
1
,
2
,
1
]
[0,1,0,2,1,0,1,3,2,1,2,1]
[0,1,0,2,1,0,1,3,2,1,2,1]可以接
6
6
6个单位的雨水。
容易想到双指针法,关键在于确定跟新指针的法则。
水最多可以装多高由左侧与右侧柱子中的较长者决定,因此每次更新时固定指向较长柱的指针;具体可以装多少水由当前较短柱侧当最高柱与较短柱的落差决定,因此需要记录当前的最高柱,并根据落差更新结果。
def trap(height):
l_index, r_index = 0, len(height) - 1
l_max, r_max = 0, 0
result = 0
while l_index < r_index:
if height[l_index] < height[r_index]:
if height[l_index] >= l_max:
l_max = height[l_index]
else:
result += l_max - height[l_index]
l_index += 1
else:
if height[r_index] >= r_max:
r_max = height[r_index]
else:
result += r_max - height[r_index]
r_index -= 1
return result