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!

class Solution {
public:
       int trap(vector<int>& a) {
        int n=a.size();
        int left=0,right=n-1;
        int res=0;
        while(left+1<right){
            while(left<right&&a[left]<=a[left+1]) left++;
            while(left<right&&a[right]<=a[right-1]) right--;
            if(left>=right) break;
			int small=a[left]<=a[right]?left:right;
            for(int i=left+1;i<right;i++){
                if(a[i]<=a[small]){
                    res+=a[small]-a[i];
                    a[i]=a[small];
                }
            }
			if(a[left]<=a[right]) left++;
			else right--;
        }
        return res;
    }
};

更好的方法:

class Solution {
public:
    int trap(vector<int>& a) {
        int n=a.size();
        int left=0,right=n-1;
        int maxleft=0;
        int maxright=0;
        int res=0;
        while(left<right){
            if(a[left]<a[right]){
                if(a[left]>=maxleft) maxleft=a[left];
                else res+=maxleft-a[left];
                left++;
            }else{
                if(a[right]>=maxright) maxright=a[right];
                else res+=maxright-a[right];
                right--;
            }
        }
        return res;
    }
};


 


你可能感兴趣的:(Trapping Rain Water)