0
点赞
收藏
分享

微信扫一扫

LeetCode刷题笔记 字节每日打卡 直方图的水量

kolibreath 2022-01-27 阅读 44

给定一个直方图(也称柱状图),假设有人从上面源源不断地倒水,最后直方图能存多少水量?直方图的宽度为 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

力扣


双指针

该方法由动态规划演化而来,具体证明见力扣

实际方法:

左指针从左往右,右指针从右往左

遍历的时候刷新对应的最大值

如果左指针对应的值比右指针低,则ans+=leftMax-height[left];左指针移动

如果右指针对应的值比左指针低,则ans+=rightMax-height[right];右指针移动

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;
    }
}

举报

相关推荐

0 条评论