您的位置:首页 > 移动开发

42. Trapping Rain Water

2016-04-30 15:18 399 查看
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!

Subscribe to see which companies asked this question

分析:

这个题目看得懂别人的解法,却不能证明正确性。

分别维护左右两边的标记l,r,每次去a[l]与a[r]中的小者,假设a[l]<a[r],对l的左边延伸,若l的右边小于a[l],则用a[l]去减就是装水的地方。一直延伸到l的右边某个点大于左边,停止。反之亦然。

我觉得需要注意的是,最外层的while判断条件,是等于也没关系,因为里面还会保证相等也不会有影响。

代码:

class Solution {

public:

    int trap(vector<int>& A) {

        int l=0,r=A.size()-1,res=0;

        while(l<r)

    
4000
    {

            int minn=min(A[l],A[r]);

            if(minn==A[l])

            {

                while(++l<r&&A[l]<=minn)

                res+=minn-A[l];

            }

            else

            {

                while(l<--r&&A[r]<=minn)

                res+=minn-A[r];

            }

        }

        return res;

    }

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  vector