面试题 17.21. 直方图的水量
给定一个直方图(也称柱状图),假设有人从上面源源不断地倒水,最后直方图能存多少水量?直方图的宽度为 1
。
上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1]
表示的直方图,在这种情况下,可以接 6
个单位的水(蓝色部分表示水)。 感谢 Marcos 贡献此图。
示例:
输入: [0,1,0,2,1,0,1,3,2,1,2,1]
输出: 6
方法一:直接计算
解题思路
根据最高点把数据拆为两部分:[0, top)
和 (top, n]
,求出两部分的雨水相加就是结果。(top, n]
反过来遍历就和 [0, top)
的解法相同,所以两个其实是一个问题:如果求 [0, top)
的雨水。
- 找出数组中的最高点
top
(有多个随便取一个就行)。 - 遍历
[0, top)
区间,维护区间内的相对最高点,后面的元素小于相对最高点则累加差值,反之更新相对最高点。 [n, top)
处理方式与[0, top)
相同。
参考代码
public int trap(int[] height) {
// 找最高点
int top = 0;
int n = height.length;
for (int i = 1; i < n; i++) {
if (height[i] > height[top]) {
top = i;
}
}
int water = 0;
// 累加左边到最高点
int h = 0;
for (int i = 0; i < top; i++) {
if (h > height[i]) {
water += h - height[i];
} else {
h = height[i];
}
}
// 累加右边到最高点
h = 0;
for (int i = n - 1; i > top; i--) {
if (h > height[i]) {
water += h - height[i];
} else {
h = height[i];
}
}
return water;
}