42. Trapping Rain Water
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1]
, return 6
.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
问题: 给定一个数组,每个元素表示海报高度,每个元素宽度均为 1 ,求这个数组能装多少雨水。
方法1
左边比右边小或者大都可以盛水,所以我们不能直接确定右边是否会有一个柱子比较大,能盛所有现在积攒的水。
那么我们就找到中间最大的那个柱子,把它分成左右两边,那么不管从左边还是右边都能保证最后可以有最高的柱子在,之前盛的水都是有效。
public int trap(int[] height) {
if (height.length <= 2)
return 0;
int res = 0;
int maxHeight = height[0];
int maxIndex = 0;
// 最大值以及最大值下标
for (int i = 1; i < height.length; i++)
if (maxHeight < height[i]) {
maxHeight = height[i];
maxIndex = i;
}
// 左边
int maxLeft = height[0];
for (int i = 1; i < maxIndex; i++) {
if (maxLeft > height[i])
res += (maxLeft - height[i]);
else
maxLeft = height[i];
}
// 右边
int maxRight = height[height.length - 1];
for (int i = height.length - 2;
i > maxIndex; i--) {
if (maxRight > height[i])
res += (maxRight - height[i]);
else
maxRight = height[i];
}
return res;
}
方法2
首先找到有效的两边,如 [0, 1, 2, 3, 0, 3, 2, 1, 0],递增的左边和递减的右边是不能盛水的。
然后选择较短的边,如果是左边就开始右移,直到找到一个比左边高的边,更新左边;如果是右边较短,就左移,直到找到一个更高的边,更新右边。
public int trap(int[] height) {
if (height.length <= 2)
return 0;
int res = 0;
int l = 0;
int r = height.length - 1;
// 跳过两边不能盛水的
while (l < r && height[l] <= height[l + 1])
l++;
while (l < r && height[r] <= height[r - 1])
r--;
// 此时l指向左侧递增序列中最高的下标
while (l < r) {
int left = height[l++];
int right = height[r--];
if (left < right) {
while (l < r && left >= height[l]) {
res += left - height[l];
l++;
}
} else {
while (l < r && right >= height[r]) {
res += right - height[r];
r--;
}
}
}
return res;
}
相似问题
11. Container With Most Water Java版(最大盛水容积)