Given n non-negative integers representing an elevation map where the width of each bar are 1, compute how much WA ter It is the 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 the Rain Water (blue section) is being trapped. Thanks Marcos for contributing this image!
Ideas:
1. First remove the leftmost 0;
2. Walk through each pillar.
3. Go to the heavy processing
Code:
classsolution{ Public: intTrapintA[],intN) {if(a==null| | n==0)return 0; inti; intres=0; for(i=0; i<n;++i) { if(a[i]!=0) Break; } intstart=i+1; Map<int,BOOL>Repeatnum; while(start<N) {if(Repeatnum.count (start)) {++start;Continue;} intLintR; for(l=start-1; l>=0;--l) { if(a[l]>A[start]) { Break; } } for(r=start+1; r<n;++r) {if(A[r]==a[start]) repeatnum[r]=true; if(a[r]>A[start]) { Break; } } if(l==-1|| r==N) { ++start;Continue; } inttemp= (min (a[l],a[r])-a[start]) * (r-l-1); Res+=temp; ++start; } returnRes; }};
Trapping Rain Water