Last Updated: July 28, 2022
·
1.552K
· njucslqq

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.

这道题来源于leetcode,据说是一道Google的面试题,这儿给出一种比较简单的解法:先计算柱状图的凸包面积,然后减去柱状图本身的面积,就是所能存储水的多少。时间复杂度:O(n),空间复杂度:O(1)。

class Solution {
//O(n) algorithm
public:
    int trap(int A[], int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(n<=2)
            return 0;
        int sum=A[0],mi=0;
        for(int i=1;i<n;i++)
        {
            sum+=A[i];
            if(A[i]>A[mi])
                mi=i;
        }
        int left=0,right=0,min=0;
        for(int i=1;i<=mi;i++)
            if(A[i]>=A[min])
            {
                left+=A[min]*(i-min);
                min=i;
            }
        min=n-1;
        for(int j=n-2;j>=mi;j--)
            if(A[j]>=A[min])
            {
                right+=A[min]*(min-j);
                min=j;
            }
        return left+right+A[mi]-sum;
    }
};

1 Response
Add your response

mine is faster

int landscape[] = {0,1,0,2,1,0,1,3,2,1,2,1};
int units = 0 ;
int startBarrrerPos = 0;

int size = sizeof(landscape)/ sizeof(int);

for(int i = 0; i < size-1; i++)
{
if ( landscape[i] >= landscape[startBarrrerPos])
{
startBarrrerPos=i;
continue;
}

if ( landscape[i+1] > landscape[i])
{
    int increment = (min(landscape[i+1], landscape[startBarrrerPos])) - landscape[i];

    if ( landscape[i+1]>= landscape[startBarrrerPos] )
        units+= increment * ((i+1 ) -(startBarrrerPos+1));
    else 
        units+=  increment;
}

}

over 1 year ago ·