The title is here: https://leetcode.com/problems/trapping-rain-water/
Label Array; Stack; Pointers
I feel very difficult about this problem, I am not at all. The following is a good way to think of others, their own appropriate to do some simple adjustment.
I think this solution is very ingenious in using two pointers. The variables used have left and right two pointers, one on the far left, one on the rightmost, and two in the middle. While walking, maintain two variables, left barrier and right barrier, that is, the bezel on the front and the bezel on the side.
Illustrate the idea with an example:
Surround a "basin" with Leftbarrier and Rightbarrier. If the height of the leftbarrier is lower than rightbarrier (e.g.), then fix the right side, try to move the left pointer, then we compare leftbarrier and Height[left], if it is height[left] smaller, We know that the part between the Leftbarrier and the left must be able to accumulate rainwater (the red part in the picture) and, if it is height[left] larger, update the leftbarrier.
Why is the rightbarrier on the right side fixed above? Because when Rightbarrier > Leftbarrier, if again encounter Height[left] < leftbarrier situation, then leftbarrier and Height[left] The area formed between them can accumulate rainwater.
Ah, that seems to be very round, but the reason is such a truth ... See if there is a better way to explain it later ... Sweat
1 Public classSolution {2 Public intTrapint[] height) {3 4 intleft = 0;5 intright = Height.length-1;6 7 intLeftbarrier = 0;8 intRightbarrier = 0;9 intresult = 0;Ten One while(Left <=Right ) { A if(Leftbarrier <=rightbarrier) { - //there could be a basin between Leftbarrier and Rightbarrier - //And left side is lower one the if(Height[left] >leftbarrier) { - //Update left barrier -Leftbarrier =Height[left]; -}Else { + //trap Water (Leftbarrier-height[left]) * 1 -Result + = Leftbarrier-Height[left]; + } Aleft++; at}Else { - if(Height[right] >rightbarrier) { - //Update right barrier -Rightbarrier =Height[right]; -}Else { - //trap Water (rightbarrier-height[right]) * 1 inResult + = Rightbarrier-Height[right]; - } toright--; + } - } the returnresult; * } $}
[Leetcode] [042] Trapping Rain water (Java)