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!
Analysis:
We scan the whole array twice. First:from head to end; Second:from end to start.
In every scan, we record the current bar for rain trapping. If the value of the current column was less than the bar and then current store + = Bar-currentvalueofcolumn; Else, current store was end, we then add the current store to the total store, and reset the bar as Currentvalueofcolumn.
Solution:
1 Public classSolution {2 Public intTrapint[] A) {3 if(a.length==0)return0;4 if(a.length==1)return0;5 intindex = 1;6 intBar = a[0];7 intTotal = 0;8 intCurstore = 0;9 Boolean[] Count =New Boolean[a.length];Ten One //We need to record which column have been counted during the first scan. A for(inti=0;i<count.length;i++) Count[i] =false; -List<integer> countlist =NewArraylist<integer>(); - the while(index<a.length) { - intCurbar =A[index]; - if(curbar<bar) { -curstore+= (bar-Curbar); + Countlist.add (index); -}Else { +Total + =Curstore; ACurstore = 0; atBar =Curbar; - for(intI=0;i<countlist.size (); i++) Count[countlist.get (i)]=true; - countlist.clear (); - } -index++; - } in -Bar = A[a.length-1]; toindex = a.length-2; +Curstore = 0; - while(index>=0){ the intCurbar =A[index]; * if(Curbar<bar &&!)Count[index]) $curstore+= (bar-Curbar);Panax Notoginseng Else if(curbar>bar) { -Total + =Curstore; theCurstore = 0; +Bar =Curbar; A } theindex--; + } - $ $ returnTotal ; - } -}
Note:we need to record which column have been counted in the first scan, We then ignor these column in the second scan.
Leetcode-trapping Rain Water