LeetCode42 蓄水池

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.

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
使用两个指针分别跟踪左右最高的条形
leftMax bar和rightMax bar中间的任何东西都不会影响当前位置陷阱的水量
我们只需要跟踪leftMax是否小于rightMax
如果是这样,请使用左栏作为当前的集装箱边缘
否则,使用右侧杆作为当前的容器边缘
不要忘记扣除当前位置的高度(试着想象当前位置的高度是基座的高度

public int trap(int[] height) {
        int leftmax = 0;
        int rightmax = 0;
        int a = 0;
        int b = height.length - 1;
        int sum = 0;
        while(a <= b){
            leftmax = Math.max(height[a], leftmax);
            rightmax = Math.max(height[b], rightmax);
            if(leftmax < rightmax){
                sum += leftmax - height[a];
                a++;
            }else{
                sum += rightmax - height[b];
                b--;
            }
        }
        return sum;
    }

猜你喜欢

转载自blog.csdn.net/fruit513/article/details/85011922
今日推荐