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(int A[], int n) {
        int result = 0;
        int l = 0,r = n-1;
        while(A[l]==0)l++;
        while(A[r]==0)r--;
        int h = 0;
        h = min(A[l],A[r]);
        while(l < r)
        {
            if(A[l] <= h)
            {
                result += h - A[l];
                l++;
            }
            else if(A[r] < h)
            {
                result += h - A[r];
                r--;
            }
            else if(A[l] > h && A[r] == h)
            {
                r--;
            }
            else if(A[r] > h && A[l] == h)
            {
                l++;
            }
            else if(A[l]>h &&A[r]>h)
            {
                h = min(A[l],A[r]);
            }
        }
        return result;
    }
};

  

posted on 2014-04-19 22:59  pengyu2003  阅读(142)  评论(0编辑  收藏  举报

导航