题目
给定 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, 7for i in range(len(height)):if height[i] == _max:breakif p1 == 0 or height[i] >= p1:p1 = height[i]continueres = res + p1 - height[i]# 从后往前遍历p2 = 0for j in range(len(height) - 1, -1, -1):if height[j] == _max:breakif p2 == 0 or height[j] >= p2:p2 = height[j]continueres = 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 0n=len(height)left,right=0,n-1ans=0maxleft=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+=1else:ans+=maxright-height[right]right-=1return ans
