首页 > 移动平台 > 详细

Trapping Rain Water 解答

时间:2019-09-14 00:08:33      阅读:94      评论:0      收藏:0      [点我收藏+]

Question

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.

技术分享图片
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!

Example:

Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6

Solution 1 -- DP

技术分享图片

关键是将问题转换成求和,考虑每一个格子的可以贡献的水量。如上图所示,每一个格子上可以储存的最大水量由它左右两边决定。

volumn = min(max_left, max_right) - height

所以我们可以用DP来算出每个格子的max_left和max_right,进而可以得到总的水量。

 1 class Solution:
 2     def trap(self, height: List[int]) -> int:
 3         if not height:
 4             return 0
 5         L = len(height)
 6         dp_right = [height[0]] + [0] * (L - 1)
 7         dp_left = [0] * (L - 1) + [height[L - 1]]
 8         result = 0
 9         for i in range(1, L):
10             dp_left[i] = max(dp_left[i - 1], height[i - 1])
11         for i in range(L - 2, 0, -1):
12             dp_right[i] = max(dp_right[i + 1], height[i + 1])
13             tmp = min(dp_left[i], dp_right[i]) - height[i]
14             if tmp > 0:
15                 result += tmp
16         return result

 

Solution 2 -- Two Pointers

双指针法,一次遍历。

 1 class Solution:
 2     def trap(self, height: List[int]) -> int:
 3         if not height:
 4             return 0
 5         l, r = 0, len(height) - 1
 6         result = 0
 7         while l < r:
 8             tmp = min(height[l], height[r])
 9             if height[l] < height[r]:
10                 l += 1
11                 while l < r and height[l] < tmp:
12                     result += tmp - height[l]
13                     l += 1
14             else:
15                 r -= 1
16                 while l < r and height[r] < tmp:
17                     result += tmp - height[r]
18                     r -= 1
19         return result

 

Trapping Rain Water 解答

原文:https://www.cnblogs.com/ireneyanglan/p/11517965.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!