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.
Ideas:
My own idea is to go through the array first to find all the peaks in the position, in the example is 1,3,7,10, and then fill the water between the two peaks, to get water
classSolution { Public: intTrapintA[],intN) {BOOLHaswater =false; Vector<int>Peak; intAns =0; for(inti =0; I < n-1; i++)//Find the first mountain { if(A[i] > a[i +1]) {peak.push_back (i); Break; } } if(Peak.empty ()) {return 0;//no valleys, no water . } intMaxHeight = a[peak[0]]; for(inti = peak[0] +1; I < n; i++)//Find the rest of the mountain { if(A[i] > A[i-1])//than the previous value of the Daxin mountain { while(A[i] > A[peak.back ()] && a[peak.back () < MaxHeight)//higher than the previous peak, and before the peak is not the peak, deleted before the first mountain can not be deleted{peak.pop_back (); } maxheight= (A[i] > MaxHeight)? A[i]: maxheight;//the new peakPeak.push_back (i); } } for(inti =0; I < peak.size ()-1; i++)//water is added to two peaks in turn { intHeight = min (a[peak[i]], a[peak[i+1]]);//The horizontal plane is the shorter of the two peaks. for(intj = Peak[i] +1; J < peak[i+1]; J + +) {ans+ = max (height-a[j),0);//Prevention of 5 4 1 2 This level is lower than the middle non-peak } } returnans; }};
The idea of the great God: not looking for all the peaks as I do, but the amount of water for each coordinate location as you traverse the edges. And the great God is contracted on both sides of the left.
classSolution { Public: intTrapintA[],intN) {intleft=0;intright=n-1; intres=0; intmaxleft=0, maxright=0; while(Left<=right) {//no traversal ends if(A[left]<=a[right]) {//If the right side is higher then the left side is processed if(A[left]>=maxleft) Maxleft=a[left];//if the current value is larger than the maximum value on the left, the update maximum will not have water at this location ElseRes+=maxleft-a[left];//if the maximum value is smaller than the left, then the current value must be on the left side of the valley smaller than the right of the left.left++; } Else{ if(a[right]>=maxright) maxright=A[right]; Elseres+=maxright-A[right]; Right--; } } returnRes; }};
"Leetcode" trapping Rain water (hard)