213 字
1 分钟
42. 接雨水:双指针维护两侧最高柱

i 个位置能接的雨水由左右最高柱中较低的一侧决定:max(0,min(Li,Ri)hi)\max(0, \min(L_i, R_i) - h_i)。预处理两组最高值可解题,但会消耗 O(n)O(n) 空间。

双指针不变量#

使用 leftright 从两端收缩,分别维护 leftMaxrightMax。若 leftMax <= rightMax,当前位置左侧的上界已经确定,右侧必然至少有 rightMax,所以可以立即结算 left;反之处理 right

class Solution {
public:
int trap(vector<int>& height) {
int n = height.size();
int l = 0, r = n - 1;
int lmax = 0, rmax = 0;
int res = 0;
while(l < r) {
lmax = max(lmax, height[l]);
rmax = max(rmax, height[r]);
if(lmax < rmax) {
res += lmax - height[l];
l ++;
}
else {
res += rmax - height[r];
r --;
}
}
return res;
}
};

时间复杂度为 O(n)O(n),额外空间为 O(1)O(1)。空数组或只有一个柱子时循环不会执行,答案自然为零。

42. 接雨水:双指针维护两侧最高柱
https://blog.xqcherry.top/posts/algorithms/trapping-rain-water-two-pointers/
作者
xqcherry
发布于
2026-09-20
许可协议
CC BY-NC-SA 4.0