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!
https://leetcode.com/problems/trapping-rain-water/
Pick up the rain, double hands.
Start with a double pointer pointing to the head and tail respectively.
Each cycle finds the highest bar on both sides, the volume of which can be determined depends on the short one, because no matter what is in between, Max on both sides is guaranteed to save the water.
1 /**2 * @param {number[]} height3 * @return {number}4 */5 varTrap =function(height) {6 vari = 0, j = height.length-1, res = 0,7Leftmax = Height[i], Rightmax =Height[j];8 while(I <=j) {9Leftmax =Math.max (Leftmax, height[i]);TenRightmax =Math.max (Rightmax, height[j]); One if(Leftmax >Rightmax) { ARes + = Rightmax-Height[j]; -j--; -}Else{ theRes + = Leftmax-Height[i]; -i++; - } - + } - returnRes; +};
[Leetcode] [JavaScript] Trapping Rain Water