接雨水:左右最高墙的较小值减去当前高度

11 阅读1分钟

[> > ******](url)

cover.png## 一、核心公式

接雨水的单点计算公式:

位置 i 存水量 = min(leftMax[i], rightMax[i]) - height[i]

二、双指针解法(最优)

var trap = function(height) {
    let left = 0, right = height.length - 1;
    let leftMax = 0, rightMax = 0, res = 0;
    while (left < right) {
        if (height[left] < height[right]) {
            if (height[left] >= leftMax) leftMax = height[left];
            else res += leftMax - height[left];
            left++;
        } else {
            if (height[right] >= rightMax) rightMax = height[right];
            else res += rightMax - height[right];
            right--;
        }
    }
    return res;
};

三、总结

  1. 核心公式:min(左最高, 右最高) - 当前高度
  2. 双指针 O(1) 空间是面试最优解