題目:給定 n 個非負整數表示每個寬度為 1 的柱子的高度圖,計算按此排列的柱子,下雨之后能接多少雨水。
思路:與第11題的思路很像
程序:
class Solution:
def trap(self, height: List[int]) -> int:
result = 0
index_left = 0
index_right = len(height) - 1
left_max = 0
right_max = 0
while index_left <= index_right:
if height[index_left] <= height[index_right]:
if height[index_left] < left_max:
result = result + (left_max - height[index_left])
else:
left_max = height[index_left]
index_left += 1
else:
if height[index_right] < right_max:
result = result + (right_max - height[index_right])
else:
right_max = height[index_right]
index_right -= 1
return result