Describe
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute
How much water it was able to the trap after raining.
For example, Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6
Analysis
For each pillar, find the tallest pillar on the left and right side, the area that the pillar can hold is min (Max_left,
Max_right)-height. So
1. Scan from left to right, and for each pillar, the left maximum value is obtained;
2. Scan from right to left, for each column, the maximum right value;
3. Scan again and add up the area of each pillar.
can also,
1. Scan once and find the highest pillar, which divides the array into two halves;
2. Handle the left half;
3. Handle the right half.
Code
1 Packagestacksandqueues;2 3 Public classTrappingrainwater {4 5 Public Static voidMain (string[] args) {6 //TODO auto-generated Method Stub7 //from left to right to find the largest, and then from right to left to find the largest, currently the largest-currently array[i]; find the smallest of them, that is, the amount of water stored. 8 int[] array= {0,1,0,2,1,0,1,3,2,1,2,1};9 System.out.println (Trap (array));Ten } One A Public Static intTrapint[] Array) { - if(Array.Length = = 0) - return0; the intLen = array.length-1; - int[] Maxl =New int[Len + 1]; - int[] MaxR =New int[Len + 1]; - intCap = 0, total = 0; + for(inti = len; I >= 0; i--) { -Maxr[i] =cap; + if(Array[i] >cap) ACap =Array[i]; at } -Cap = 0; - for(inti = 0; I <= Len; i++) { -Maxl[i] =cap; - if(Array[i] >cap) -Cap =Array[i]; in } - for(inti = 0; I <= Len; i++) { to intc = Math.min (Maxl[i], maxr[i])-Array[i]; + if(C > 0) -Total + =C; the } * returnTotal ; $ }Panax Notoginseng}
Trapping Rain Water