面试题 17.21. 直方图的水量
难度困难121
给定一个直方图(也称柱状图),假设有人从上面源源不断地倒水,最后直方图能存多少水量?直方图的宽度为 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
通过次数15,503提交次数24,296
Code:dp
class Solution {
//时间复杂度O(n)空间复杂度O(n)
public int trap(int[] height) {
int n=height.length;
if(n<2) return 0;
int leftmax[]=new int [n];
int rightmax[]=new int [n];
int sum=0;
leftmax[0]=height[0];
for(int i=1;i<n;i++)//得到每一个点的左边最大高度
leftmax[i]=Math.max(leftmax[i-1],height[i]);
rightmax[n-1]=height[n-1];
for(int i=n-2;i>=0;i--)//得到每一个点的右边最大高度
rightmax[i]=Math.max(rightmax[i+1],height[i]);
for(int i=0;i<n;i++)//改点可以容纳的水就是左右边最小高度再减去当前高度
sum+=(Math.min(leftmax[i],rightmax[i])-height[i]);
return sum;
}
}
Code: 双指针 参考官方题解
class Solution {
public int trap(int[] height) {
int ans = 0;
int left = 0, right = height.length - 1;
int leftMax = 0, rightMax = 0;
while (left < right) {
leftMax = Math.max(leftMax, height[left]);
rightMax = Math.max(rightMax, height[right]);
if (height[left] < height[right]) {
ans += leftMax - height[left];
++left;
} else {
ans += rightMax - height[right];
--right;
}
}
return ans;
}
}