42. 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!

解决方法:

不按高度*宽度来计算水面积,而是以累积的方式来考虑。 
从左至右搜索,分别记录左右的最大高度maxLeft和maxRight,它们就像容器的两面墙。 固定较高的一个,让水从相对矮的一边流。
例如,如果当前左边的高度较低(maxLeft < maxRight),我们从容器的左边加水。

直到左边遇见右边,我们填满整个容器。

代码如下:

class Solution {
public:
    int trap(vector<int>& height) {
        int left = 0; int right = height.size()-1;  //左右墙的下标
        int res = 0;
        int maxleft = 0, maxright = 0;
        while(left <= right){     //左右墙不相遇
            if(height[left] <= height[right]){     //容器的左墙低,那按照左边高度向下流水。
                if(height[left] >= maxleft) maxleft = height[left]; //遇到更高的高度,水流停止。且重新赋值maxleft,
                else res += maxleft-height[left];  //遇到矮的高度,就向下流水,水量是当前高度与maxleft之差
                left++;                                            
            }
            else{
                if(height[right] >= maxright) maxright = height[right];
                else res += maxright - height[right];
                right--;
            }
        }
        return res;
    }
};
原文地址:https://www.cnblogs.com/hozhangel/p/7861748.html