42. 接雨水

image

42. 接雨水

思路

要解决接雨水问题,核心思路是计算每个位置能接的雨水量,即该位置左右两侧最高柱子的较小值减去当前柱子的高度。使用双指针法可以在 O(n) 时间内完成,空间复杂度 O(1)。

  1. 初始化指针和变量

    • left 指针在数组起始位置
    • right 指针在数组末尾
    • left_max 记录从左到右遍历时的最大高度
    • right_max 记录从右到左遍历时的最大高度
    • ans 累计总雨水量
  2. 移动指针并计算雨水

    • height[left] < height[right] 时:

      • 如果 height[left] > left_max,更新 left_max,此时当前柱子位置无法接水
      • 否则,当前柱子能接的雨水量为 left_max - height[left]
      • 左指针右移
    • height[left] >= height[right] 时:

      • 如果 height[right] > right_max,更新 right_max
      • 否则,当前柱子能接的雨水量为 right_max - height[right]
      • 右指针左移

复杂度分析

  • 时间复杂度:O(n),其中n是数组长度。进行了两次独立遍历
  • 空间复杂度:O(1),只使用了常数级别的额外空间

代码

class Solution {
    public int trap(int[] height) {
        if (height.length == 0) return 0;
        
        int left = 0, right = height.length - 1;
        int left_max = 0, right_max = 0;
        int ans = 0;
        
        while (left < right) {
            if (height[left] < height[right]) {
                if (height[left] > left_max) {
                    left_max = height[left];
                } else {
                    ans += left_max - height[left];
                }
                left++;
            } else {
                if (height[right] > right_max) {
                    right_max = height[right];
                } else {
                    ans += right_max - height[right];
                }
                right--;
            }
        }
        return ans;
    }
}

posted @ 2025-08-01 01:38  quanht  阅读(5)  评论(0)    收藏  举报