42. 接雨水

给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。

示例 1:

输入:height = [0,1,0,2,1,0,1,3,2,1,2,1]
输出:6
解释:上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。 

示例 2:

输入:height = [4,2,0,3,2,5]
输出:9

提示:

  • n == height.length
  • 1 <= n <= 2 * 104
  • 0 <= height[i] <= 105
public int trap(int[] height) {
        return method1(height, height.length);
    }

    /**
     * 贪心 + 双指针
     * 1 ms
     * 复杂度O(n)
     */
    public int method1(int[] height, int n) {
        int i = 0, j = n - 1;
        int leftMax = 0, rightMax = 0;
        int sum = 0;
        while (i < j) {
            // 获取左右边界的最高值
            leftMax = Math.max(leftMax, height[i]);
            rightMax = Math.max(rightMax, height[j]);
            // 小的那个需要移动,因为短桶效应,需要找到长的桶
            sum += leftMax < rightMax ? leftMax - height[i++] : rightMax - height[j--];
        }
        return sum;
    }

Tags:

No responses yet

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

🛡️ 闽ICP备2024065179号-3