# 42. Trapping Rain Water

## Solution 1：

class Solution:
def trap(self, height: List[int]) -> int:
if not height:
return 0
lo, hi = 0, len(height)-1
target, boundary = 1, max(height) #计算黑色和蓝色的面积之和，从第一层开始算，最高层为boundary
res = 0
while lo < hi or target <= boundary:
while lo <= hi and height[lo] < target:
lo += 1
while lo <= hi and height[hi] < target:
hi -= 1
res += (hi-lo+1) # hi-lo+1为每一层的宽度
target += 1
return res - sum(height)


## Solution 2：官方题解-动态规划

class Solution:
def trap(self, height: List[int]) -> int:
if not height:
return 0
res, size = 0, len(height)
left_max, right_max = [0]*size, [0]*size
left_max[0] = height[0]
for i in range(1, size):
left_max[i] = max(left_max[i-1], height[i])
right_max[-1] = height[-1]
for i in range(size-2, -1, -1):
right_max[i] = max(right_max[i+1], height[i])
for i in range(size):
res += min(left_max[i], right_max[i]) - height[i]
return res

• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 手机看

分享到微信朋友圈

x

扫一扫，手机阅读

• 打赏

打赏

ISimle

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文
01-20 70

03-10 1万+
12-08 5734