[LeetCode] Trapping Rain Water 搜集雨水

相关问题:一个int数组, 比如 array[],里面数据无任何限制,要求求出 所有这样的数array[i],其左边的数都小于等于它,右边的数都大于等于它。能否只用一个额外数组和少量其它空间实现

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!

思路:这个数组中每个位置上能保存的雨水量,取决于该位置左边的数组元素最大值max_1,和该位置右边的数组元素最大值max_2,如果max_1>current element而且max_2>current element,那么该位置上能保存的雨水就是 min(max_1, max_2) - current element。

代码如下:

    int trap(int A[], int n) {
        
        if(n==0 || n==1 || n==2)
            return 0;
            
        int water = 0; // amount of water to be held
        
        int* B = new int[n-2];  // max values for each current element from left to right
        int* C = new int[n-2];  // max values for each current element from right to left
        int max_1 = A[0], max_2 = A[n-1];  // 
        
        for(int i=1; i<n-1; i++)
        {
            B[i-1] = max_1;
            max_1 = max(max_1, A[i]); // update global max
        }
        
        for(int j=n-2; j>0; j--)
        {
            C[n-2-j] = max_2;
            max_2 = max(max_2, A[j]); // update global max
        }
        
        for(int i=0; i<n-2; i++)
        {
            if(B[i]>A[i+1] && C[n-3-i]>A[i+1])
                water = water + min(B[i], C[n-3-i])-A[i+1];
        }
        
        return water;
    }

上面的算法需要从左往右扫描一次,从右往左扫描一次,一共两次。

http://blog.csdn.net/linhuanmars/article/details/20888505给出一个只需扫描一次的算法。

你可能感兴趣的:([LeetCode] Trapping Rain Water 搜集雨水)