面试题 17.21. 直方图的水量
地址:https://leetcode-cn.com/problems/volume-of-histogram-lcci/
给定一个直方图(也称柱状图),假设有人从上面源源不断地倒水,最后直方图能存多少水量?直方图的宽度为 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
解题思路:对撞指针
class Solution {
public int trap(int[] height) {
if (height.length <= 1) {
return 0;
}
int volume = 0;
// 记录左右最大高度
int leftMax = height[0];
int rightMax = height[height.length-1];
// 左右指针
int left = 0;
int right = height.length - 1;
while (left < right) {
// 用于移动指针,if成立,移动左指针,否则,移动右指针
if (height[left] < height[right]) {
// 更新最大值
maxLeft = Math.max(height[left], maxLeft);
// 获取雨水
res += maxLeft - height[left];
left ++;
}else {
maxRight = Math.max(height[right], maxRight);
res += maxRight - height[right];
right --;
}
}
return volume;
}
}
单调栈
建立一个单调递减的栈,如果出现一个元素比栈顶元素大的话,必然可以形成凹槽,此时我们只需要计算凹槽长度和边界的高度差那么必然可以计算出接水的面积。
Cest la vie!