70.Trapping Rain Water (water capacity)

Level:

  Hard

Subject description:

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.

img
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 rain water (blue section) are being trapped. Thanks Marcos for contributing this image!

Example:

Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6

Analysis of ideas:

  Two pointers arranged left and right, respectively, end-point position of the array, and then scanned from both sides toward the middle, two pointer within the current range is determined, to find two small comparison value, if the value is a value smaller points left, then scanned from left to right, if a smaller value is right to point value, then right to left scan, if the value is less than the current encounter smaller value, the difference will be credited result, if encountered a large value, the new window is re-determined range, and so on until the left and right pointers coincide.

Code:

public class Solution{
    public int trap(int[]height){
        int left=0;
        int right=height.length-1;
        if(height==null||height.length==0)
            return 0;
        int res=0;
        while(left<right){
            int min=Math.min(height[left],height[right]); //找到两端较小的值
            if(min==height[left]){
                ++left;
                while(left<right&&height[left]<min){
                    res=res+min-height[left];
                    left++;
                }
            }else{
                --right;
                while(left<right&&height[right]<min){
                    res=res+min-height[right];
                    right--;
                }
            }
        }
        return res;
    }
}

Guess you like

Origin www.cnblogs.com/yjxyy/p/11098010.html