描述
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.
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
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!
分析
我们要得到每一个bar的储水量,需要知道它左右最大高度,用 min(max_left,max_right) - height
(height当前bar的高度)。可以得到公式container[i] = min(max_left[i],max_right[i])-height[i]
。根据这个公式我们进行两次扫描:
方法一: O(n),O(n)
1、从左到右找到左边最高的柱子。
2、从右到左 找到右边最高的柱子。
3、[0,n) 计算 总的面积。
从两边各扫描一次得到我们想要维护的变量,这个一个常用的技巧。
方法二:优化 O(n),O(1)
1、从两边往中间搜索,跟新A[0,left],A[right,n]
的最大值 maxLeft和maxRight
2、如果 maxLeft<maxRight
说明左边 maxLeft-A[i]
的水量一定可以加入,因为右边有个更高的屏障
3、同理 则maxRiht-A[i]
可以加入
复杂度:O(N), 空间需要一个长度为n的数组,复杂度也是O(N)
代码
方法一:
方法二:
参考
http://blog.csdn.net/cinderella_niu/article/details/43482897
http://www.sohu.com/a/153858619_466939 //漫画动态规划