Title:
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!
Rookie really does not, see other people's ideas.
Two better ideas, one is to find the highest peak, and then separate from both sides. Record the current highest in the closer, see http://www.cnblogs.com/lichen782/p/Leetcode_Trapping_Rain_Water.html
First, find the highest pillar, such as 3 in the example.
Then traverse the left half. From I=0 to mid, the Traverse Process maintains a curheightthat represents the maximum height value that is currently encountered, and if the current bar's height is less than the maximum value, the current bar can contribute water height-curmaxheight. Otherwise, update curmaxheight.
To get a better understanding of the algorithm, let's track the process:
classsolution{ Public: intTrap (vector<int> &height) { if(Height.size () <=1 ) return 0; intn =height.size (); intHi_index =0; for(inti =0; I < height.size (); i++){ if(height[i]>Height[hi_index]) {Hi_index=i; } } intCur_h =0; intWater =0; for(inti =0; i < Hi_index; i++){ if(Height[i] >cur_h) Cur_h=Height[i]; Else{Water+ = (Cur_h-Height[i]); }} cur_h=0; for(inti = height.size ()-1; i > Hi_index; i--){ if(Height[i] >cur_h) Cur_h=Height[i]; ElseWater+ = (Cur_h-Height[i]); } returnwater; }};
The second way of thinking is to use a monotonic stack. Here is the monotonically descending stack.
intTrap (vector<int> &height) {Stack<int> Stk;//Descending intresult =0; inti =0; intn =height.size (); while(I <N) {if(stk.size () = =0|| Height[stk.top ()] >Height[i]) {Stk.push (i);//The indexi++; } Else{//A[i] >= stk.top (); intj =Stk.top (); Stk.pop (); if(Stk.size ()! =0) {result+ = (I-stk.top ()-1) * (min (Height[stk.top (), height[i])-Height[j]); } } } returnresult; }
Leetcode:trapping Rain Water