🌊 接雨水算法可视化

使用 双指针法 (Two Pointers) 的动态演示

柱子 (Height)
雨水 (Water)
左指针 (Left)
右指针 (Right)

当前状态

左侧最高 (LeftMax)
0
右侧最高 (RightMax)
0
当前接水总量 (Total)
0

算法逻辑讲解:

点击“开始演示”或“单步执行”开始...
速度:

核心算法代码 (JavaScript)

let left = 0, right = height.length - 1;
let leftMax = 0, rightMax = 0;
let ans = 0;

while (left < right) {
    leftMax = Math.max(leftMax, height[left]);
    rightMax = Math.max(rightMax, height[right]);

    // 谁小移谁,这是核心逻辑
    if (height[left] < height[right]) {
        ans += leftMax - height[left]; // 左边矮,瓶颈在左边,此时右边必有高墙挡水
        left++;
    } else {
        ans += rightMax - height[right];
        right--;
    }
}