Trapping Rain Water
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!
Algorithm ideas:
The short plate effect, the tank is related to the short plate. Find the longest plate in the height array, then iterate from both ends to the long plate, meet the shorter to find the amount of the shelf, and meet the longer, then update the edge.
The code is as follows:
1 Public classSolution {2 Public intTrapint[] height) {3 if(Height = =NULL|| Height.length <3)return 0;4 intMax =0;5 for(inti =0; I < height.length;i++){6 if(Height[i] > Height[max]) max =i;7 }8 intHigh =0, res =0;9 for(inti =0; i < Max; i++){Ten if(Height[i] <Height[high]) { OneRes + = Height[high]-Height[i]; A}Else if(Height[i] >Height[high]) { -High =i; - } the } -High = Height.length-1; - for(inti = height.length-1; i > Max; i--){ - if(Height[i] <Height[high]) { +Res + = Height[high]-Height[i]; -}Else if(Height[i] >Height[high]) { +High =i; A } at } - returnRes; - } -}
Specific algorithm analysis can be referred to here.