基础知识要求:
Java:方法、数组、while循环、if else语句、自增自减运算符
Python: 方法、列表、while循环、if else语句
题目:
给定 n
个非负整数表示每个宽度为 1
的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
示例 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 个单位的雨水(蓝色部分表示雨水)。
示例 2:
输入:height = [4,2,0,3,2,5] 输出:9
提示:
n == height.length
1 <= n <= 2 * 104
0 <= height[i] <= 105
思路解析:
为了计算下雨后柱子能接多少雨水,我们可以使用双指针的方法。基本思路是,对于数组中的每个位置,我们需要找到其左边和右边最高的柱子。雨水的高度将由这两个最高柱子中的最小值与当前柱子高度的差值决定(如果差值大于0)。
我们可以从两端开始,使用两个指针 left
和 right
分别指向数组的开始和结束。同时,我们需要记录到当前位置为止,左边和右边出现的最高柱子的高度 leftMax
和 rightMax
。
然后,我们移动 left
和 right
指针中指向较低柱子高度的那个,并计算该位置可以接的雨水量。同时,更新 leftMax
或 rightMax
的值(如果当前柱子的高度大于之前的最大值)。
Java代码示例:
public class Solution {
public int trap(int[] height) {
int n = height.length;
if (n <= 2) {
return 0; // 柱子少于3个,无法积水
}
int left = 0, right = n - 1;
int leftMax = height[left], rightMax = height[right];
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;
}
}
Solution solution = new Solution();
int[] height = {0,1,0,2,1,0,1,3,2,1,2,1};
System.out.println(solution.trap(height)); // 输出: 6
int[] height2 = {4,2,0,3,2,5};
System.out.println(solution.trap(height2)); // 输出: 9
Python代码示例:
def trap(height):
if len(height) <= 2:
return 0 # 如果柱子少于3个,无法积水
left = 0
right = len(height) - 1
left_max = height[left]
right_max = height[right]
water = 0
while left < right:
if height[left] < height[right]:
if height[left] > left_max:
left_max = height[left] # 更新左边最大高度
else:
water += left_max - height[left] # 计算积水量
left += 1 # 左指针右移
else:
if height[right] > right_max:
right_max = height[right] # 更新右边最大高度
else:
water += right_max - height[right] # 计算积水量
right -= 1 # 右指针左移
return water
# 示例
heights = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]
print(trap(heights)) # 输出: 6
heights2 = [4, 2, 0, 3, 2, 5]
print(trap(heights2)) # 输出: 9