[leetcode] Trapping Rain Water

来源:互联网 发布:手机qq网络硬盘 编辑:程序博客网 时间:2024/06/01 08:36

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 maxi=0,sum1=0,sum0=0,max=0;        for(int i=0;i<n;i++){            sum0+=A[i];            if(A[i]>max){                 maxi=i;                max=A[i];            }        }        for(int i=1;i<maxi;i++){            if(A[i]<A[i-1]) A[i]=A[i-1];        }        for(int i=n-2;i>maxi;i--){            if(A[i]<A[i+1]) A[i]=A[i+1];        }        for(int i=0;i<n;i++){            sum1+=A[i];        }        return sum1-sum0;    }};


0 0
原创粉丝点击