美文网首页算法
接雨水问题

接雨水问题

作者: 小鱼嘻嘻 | 来源:发表于2020-11-21 15:18 被阅读0次

问题1

盛水最多的容器

原理

  • 首先想到最多的容器肯定是:Min(两个柱子)*(柱子之间间距)
  • 遍历一次需要找到最多的容器,应该采用双指针算法,并且使用max作为临时变量记录下来

代码

class Solution {
    public int maxArea(int[] arr) {
      if(arr==null||arr.length<=0){
            return 0;
        }
        int max = Integer.MIN_VALUE;
        int low = 0;
        int high = arr.length-1;

        while(low<high){
            int cur = Math.min(arr[low],arr[high]);
            max = Math.max(max,cur*(high-low));
            if(arr[low]<arr[high]){
                low++;
            }else{
                high--;
            }
        }
        return max;
    }
}

注意事项

  • 注意联想到双指针就能cover住

问题2

接雨水的总和最大

原理

  • 处理这个问题还是需要使用双指针
  • 雨水的最大值应该是min(Math.max(height[left],leftMax),Math.max(height[right],rightMax)) 简单解释就是左边最大值和右边最大值,之后的最小值决定了两边围栏的高度。当前实际的蓄水量减去当前值就OK了。

代码

class Solution {
    public int trap(int[] arr) {
        if(arr==null||arr.length<=0){
            return 0;
        }
        int max = 0;
        int low = 0;
        int high = arr.length-1;

        int leftmax = arr[0];
        int rightmax = arr[arr.length-1];

        while(low<high){
            leftmax = Math.max(leftmax,arr[low]);
            rightmax = Math.max(rightmax,arr[high]);

            if(arr[low]<arr[high]){
                max += Math.min(leftmax,rightmax)-arr[low];
                low++;
            }else{
                max += Math.min(leftmax,rightmax)-arr[high];
                high--;
            }
        }
        return max;
    }
}

注意事项

  • 注意雨水存储实际上一个一个比较计算出来的。
  • 解决问题的关键在于min(Math.max(height[left],leftMax),Math.max(height[right],rightMax))- min(height[low],height[high]);

问题3

柱状图中最大的矩形

原理

代码


注意事项

相关文章

  • 接雨水问题

    问题1 盛水最多的容器 原理 首先想到最多的容器肯定是:Min(两个柱子)*(柱子之间间距) 遍历一次需要找到最多...

  • 接雨水问题

    给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。 输入: [0,...

  • 接雨水问题

    问题描述 给定一个整形数组arr,已知其中所有的值都是非负的,将这个数组看作一个柱子高度图,计算按此排列的柱子,下...

  • 接雨水

    给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。 上面是由数组 ...

  • 接雨水

    题目来源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/trap...

  • 接雨水

    给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。 上面是由数组 ...

  • 接雨水

    https://leetcode-cn.com/explore/interview/card/bytedance/...

  • 接雨水

    给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。 上面是由数组 ...

  • 接雨水

    来源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/trappi...

  • 接雨水

    题目: 题目的理解: 从示例图中可以很好的理解,题目的意思,真的是题目描述越少越难。最直接的思路:(1)为一个高度...

网友评论

    本文标题:接雨水问题

    本文链接:https://www.haomeiwen.com/subject/ulceiktx.html