给定 n
个非负整数表示每个宽度为 1
的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
参考视频
正确思路
不管中间隔多少柱子,只看左右两侧的最高柱子,接水量只取决于左右两侧最高柱子中较矮的那根。
接水量=左右两侧较矮的柱子 - 本身高度
class Solution {
public int trap(int[] height) {
// 初始化左右指针
int l = 0, r = height.length - 1;
// 初始化左右两侧最大值
int lmax = 0, rmax = 0;
// 初始化接水量
int ans = 0;
// 双指针循环
while(l < r) {
// 计算左右两侧最大值
lmax = Math.max(lmax, height[l]);
rmax = Math.max(rmax, height[r]);
// 左右两侧较小
// 左侧较小,如左图
if(lmax < rmax) {
ans += lmax - height[l];
l++;
}
// 右侧较小,如右图
else {
ans += rmax - height[r];
r--;
}
}
return ans;
}
}