给定 n
个非负整数表示每个宽度为 1
的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
具体步骤如下:
- 如果输入数组为空,直接返回 0。
- 初始化左右指针
left
和right
,分别指向数组的左右端点。 - 初始化
left_max
和right_max
分别记录左右两侧的最大高度。 - 初始化
result
变量,用来累积存储的雨水单位。 - 当
left
小于right
时,执行以下操作:- 如果
height[left]
小于height[right]
,说明左侧是瓶颈,更新left_max
并计算左侧能存储的雨水单位,然后将left
指针右移。 - 否则,说明右侧是瓶颈,更新
right_max
并计算右侧能存储的雨水单位,然后将right
指针左移。
- 如果
- 最终返回
result
作为答案。
from typing import List
class Solution:
def trap(self, height: List[int]) -> int:
if not height:
return 0
left, right = 0, len(height) - 1
left_max, right_max = 0, 0
result = 0
while left < right:
if height[left] < height[right]:
if height[left] >= left_max:
left_max = height[left]
else:
result += left_max - height[left]
left += 1
else:
if height[right] >= right_max:
right_max = height[right]
else:
result += right_max - height[right]
right -= 1
return result
# 测试代码
sol = Solution()
height = [0,1,0,2,1,0,1,3,2,1,2,1]
result = sol.trap(height)
print(result)