Trapping Rain WaterTotal accepted:35650 Total submissions:118319my submissions QuestionSolution
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 .
At first glance, the idea is to find all the "groove", on the basis of the separate calculation of each part of the storage volume, so the most critical is the "groove" of the start and end of the definition
Finally, the use of the stack to find the appropriate (starting point: the height of the next height to start diminishing), how to define the end point? (Destination: A point with a high descent and a lower position than the left)
But there are a few questions to note:
1. When the middle appears with the same height as the left boundary, it needs to be terminated in a timely manner, because the end condition when calculating the fragment is to reach the left boundary value
2. Close to the rear if there is no strict "groove" in accordance with our provisions, from the tail to deal with each other, and in the middle value greater than the right side as the boundary height of the time to replace
The code is as follows:
classSolution {Private: intcontain; Stack<int>record; Public: intTrap (vector<int>&height) {contain=0; //keep every pair of concave shape intSize =height.size (); if(Size = =0) returncontain; intLeft, right;//record all the pairsRecord.push (height[0]); for(inti =1; i<size;) {//Left-bound if(i< size&&height[i]<Record.top ()) { Left=Record.top (); Record.push (Height[i]); } Else{Record.push (height[i]); I++; Continue; } I++; while(i<size&& (height[i]>=record.top () | | Height[i]<record.top () &&record.top () <Left )) {Record.push (height[i]); if(height[i++] = = left)//handle the same height concave shape Break; } //Calculate the container intTemp//Temp Stores the temporary right bound if(I! =size) {Temp= Record.top ();//As the pre pair ' s right-bound and new pair ' s left-boundRecord.pop (); } Else{//handle the last several elementstemp =Record.top (); Record.pop (); while(Record.top ()!=left&&temp <Record.top ()) {Temp=Record.top (); Record.pop (); } } intRefer = (Left > temp?)temp:left); while(true){ inth =Record.top (); Record.pop (); if(H = =Left ) Break; if(Refer >h) contain+ = refer-h; Else if(refer = = temp)//Short Board on the rightRefer =temp=h; } record.push (temp); } returncontain; } };
Test Case:
The simplest is an example diagram;
Height dropped not up to reach left border height
Height of the same height as the left boundary during descent
Trapping Rain water Many details to be noted