LeetCode第42题是“接雨水”,要求计算能够接住多少雨水。以下是Java的解答,并在每行添加了注释:
public class Solution {
public int trap(int[] height) {
// 特殊情况处理,如果数组长度小于3,无法形成凹槽,返回0
if (height == null || height.length < 3) {
return 0;
}
int left = 0; // 左指针
int right = height.length - 1; // 右指针
int leftMax = 0; // 左边的最大高度
int rightMax = 0; // 右边的最大高度
int water = 0; // 记录接的雨水总量
// 当左指针小于右指针时进行循环
while (left < right) {
// 如果左边的高度小于右边
if (height[left] < height[right]) {
// 如果当前高度大于左边最大高度,更新左边最大高度
if (height[left] >= leftMax) {
leftMax = height[left];
} else {
// 否则计算可以接的雨水
water += leftMax - height[left];
}
left++; // 移动左指针
} else { // 右边高度小于或等于左边
// 如果当前高度大于右边最大高度,更新右边最大高度
if (height[right] >= rightMax) {
rightMax = height[right];
} else {
// 否则计算可以接的雨水
water += rightMax - height[right];
}
right--; // 移动右指针
}
}
// 返回计算出的雨水总量
return water;
}
}
解释:
- 使用双指针法,一个从左向右遍历,一个从右向左遍历。
leftMax
和rightMax
用于记录从左到右和从右到左的最大高度。- 每一步判断左右哪个较小,较小的一侧决定了当前可以接的水量。
- 水量计算:较小侧的最大高度减去当前高度。
- 通过不断移动左右指针,最终得到接雨水的总量。