https://oj.leetcode.com/problems/trapping-rain-water/
Trapping Rain Water
Given n non-negative integers representing an elevation map where the width of each bar are 1, compute how much water it is 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!
Solution 1:
Scan from left to right, calculate to the highest bar from left to Curr, scan right to left, calculate to the highest bar from right to Curr.
Scan again, the lower of the two as the height of the {barrel}, if the barrel is higher than a[i] bar, then a[i] This bar can store height-a[i] so much water. Add up all the water.
1 Public classSolution {2 Public intTrapint[] A) {3 if(A = =NULL) {4 return 0;5 }6 7 intMax =0;8 9 intLen =a.length;Ten int[] left =New int[Len]; One int[] right =New int[Len]; A - //count the highest bar from the left to the current. - for(inti =0; i < Len; i++) { theLeft[i] = i = =0? A[i]: Math.max (Left[i-1], a[i]); - } - - //count the highest bar from right to current. + for(inti = len-1; I >=0; i--) { -Right[i] = i = = Len-1? A[i]: Math.max (right[i +1], a[i]); + } A at //count the largest water which can contain. - for(inti =0; i < Len; i++) { - intHeight =math.min (Right[i], left[i]); - if(Height >A[i]) { -Max + = height-A[i]; - } in } - to returnMax; + } -}View Code
CODE:
Https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/array/Trap.java
Leetcode:trapping Rain Water Problem Solving report