Question
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 .
Solution
Referrence
The Key to the solution was to know, which for each point a[i], and the max is was calculated by:
Min (left,right) –a[i]
Left was the maximum height before a[i], right was the maximum height after a[i].
Therefore, we can create a. Arrays to the record left of most of the height and right of most of the height for each point. Time complexity O (n).
1 Public classSolution {2 Public intTrapint[] height) {3 if(Height = =NULL|| Height.length < 1)4 return0;5 intLength =height.length;6 int[] leftmost =New int[length];7 int[] rightmost =New int[length];8 //First , find left biggest hight9Leftmost[0] = 0;Ten for(inti = 1; i < length; i++) OneLeftmost[i] = Math.max (leftmost[i-1], height[i-1]); A - //Then , find right biggest hight -Rightmost[length-1] = 0; the for(inti = length-2; I >= 0; i--) -Rightmost[i] = Math.max (rightmost[i + 1], Height[i + 1]); - - //Calculate sum + intresult = 0; - for(inti = 0; i < length; i++) { + intTMP = Math.min (Leftmost[i], rightmost[i])-Height[i]; A if(tmp > 0) atResult + =tmp; - } - returnresult; - } -}
Trapping Raining Water Solution