LeetCode42. 接雨水

LeetCode42. 接雨水_第1张图片
解题思路

  1. 从数组下标0开始进行遍历,计算每一个单元能够容纳的水量是多少,然后进行求和。(不知道能不能实现或者实现很困难)

  2. 每个单元能够存储的水量取决于左右两侧"墙"的最大值中的最小值。

  3. 尝试先遍历出每个单元左侧"墙"和右侧"墙"的最大值,然后进行循环遍历,利用公式:

    ​ water=min(leftMax,rightMax)-x

  4. 使用双指针,计算左指针左侧最大值leftMax和右指针右侧最大值rightMax,然后利用上面公式计算。

class Solution {
    public int trap(int[] height) {
        int N=height.length;
        if(N<=2) return 0;

        int L=1;
        int leftMax=height[0];
        int R=N-2;
        int rightMax=height[N-1];
        int water=0;

        while(L<=R){
            if(leftMax<=rightMax){
                water+=Math.max(0,leftMax-height[L]);
                leftMax=Math.max(leftMax,height[L++]);
            }
            else{
                water+=Math.max(0,rightMax-height[R]);
                rightMax=Math.max(rightMax,height[R--]);
            }
        }
        return water;
    }
}

你可能感兴趣的:(LeetCode,牛客,leetcode,java,指针)