Trapping Rain Water

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!


分析
空间复杂度O(n)
对于每个柱子,找到其左右两边最高的柱子,该柱子能容纳的面积就是 min(max_left,max_right) - height。所以
1. 从左往右扫描一遍,对于每个柱子,求取左边最大值;
2. 从右往左扫描一遍,对于每个柱子,求最大右值;
3. 再扫描一遍,把每个柱子的面积并累加。
  1. class Solution {
  2. public:
  3. int trap(vector<int>& height) {
  4. int length=height.size();
  5. int *max_left=new int[length]();
  6. int *max_right=new int[length]();
  7. for(int i=1;i<length;i++){
  8. max_left[i]=max(max_left[i-1],height[i-1]);
  9. max_right[length-i-1]=max(max_right[length-i],height[length-i]);
  10. }
  11. int sum=0;
  12. for (int i=0;i<length;i++){
  13. int h=min(max_left[i],max_right[i]);
  14. if(h>height[i])
  15. sum+=h-height[i];
  16. }
  17. delete[]max_left;
  18. delete[]max_right;
  19. return sum;
  20. }
  21. };

也可以,该方法空间复杂度O(1)
1. 扫描一遍,找到最高的柱子,这个柱子将数组分为两半;
2. 处理左边一半;
3. 处理右边一半。
 
  1. class Solution {
  2. public:
  3. int trap(vector<int>& height) {
  4. int max = 0; // 最高的柱子,将数组分为两半
  5. int n=height.size();
  6. for (int i = 0; i < n; i++)
  7. if (height[i] > height[max]) max = i;
  8. int water = 0;
  9. for (int i=0,peak=0;i<max;i++){
  10. if(peak<height[i])peak=height[i];
  11. else
  12. water+=peak-height[i];
  13. }
  14. for(int j=n-1,peak=0;j>max;j--){
  15. if(peak<height[j])peak=height[j];
  16. else
  17. water+=peak-height[j];
  18. }
  19. return water;
  20. }
  21. };






posted @ 2016-03-16 20:24  copperface  阅读(144)  评论(0编辑  收藏  举报