原题链接
解题思路
我们首先找出数组height中最高墙(top)的位置(top_index)。那么,对于墙的左侧部分,right_max已经确定;对于墙的右侧,left_max已经确定(都等于top)。 之后对左右侧分别求蓄水量,期间分别维护left_max和right_max即可。
代码
class Solution:
def trap(self, height: List[int]) -> int:
result=0
if len(height)<3:
return 0
top=max(height)
top_index=height.index(max(height))
max_left=height[0]
max_right=height[-1]
if top_index>=1:
for i in range(1,top_index,1):
result+=max(0,min(max_left,top)-height[i])
max_left=max(max_left,height[I])
if top_index<len(height)-1:
for i in range(len(height)-1,top_index,-1):
result+=max(0,min(max_right,top)-height[i])
max_right=max(max_right,height[i])
return result