接雨水
约 297 字小于 1 分钟
接雨水
题目描述
给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
示例
输入:height = [0,1,0,2,1,0,1,3,2,1,2,1]
输出:6
解释:上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。
输入:height = [4,2,0,3,2,5]
输出:9解析
双指针:
- 某一列能接多少水取决于左右最高柱子总较矮的那一个,再减去当前位置高度
- Water = Math.min(leftMax, rightMax) - height[i];
- 维护 left、right 两个指针,leftMax、rightMax 两个最大值变量
- 根据贪心算法,更新存水数量和较矮的一方指针,求出总储蓄值
代码
class Solution {
public int trap(int[] height) {
int left = 0, right = height.length - 1, leftMax = 0, rightMax = 0, res = 0;
while (left < right) {
leftMax = Math.max(leftMax, height[left]);
rightMax = Math.max(rightMax, height[right]);
if (leftMax < rightMax) {
res += leftMax - height[left];
left++;
} else {
res += rightMax - height[right];
right--;
}
}
return res;
}
}