leetCode:Container With Most Water

题目

Given n non-negative integers a1, a2, …, an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

题意解析:

 a[i]:以索引i为x轴坐标,a[i]为y坐标,得到一个x-y轴的点。点到x轴的距离设置为容器的高,两点之间的x轴距离设为宽。求两点,使得三条线(两个索引的距离线,两条高)围成的容器装水最多。由于短板效应,所以计算公式为:索引距离*min(height1, height2)。

思路:

 从最大宽度开始,①从高较短的点为向里收缩移动。如果这一次移动到的点的高大于上一个位置的点的高,则计算面积,若面积大于已知的最大值,则找到新的两个点。重复①操作,直至两个点会合。

AC代码

    public int maxArea(int[] height){
    int right = height.length - 1;
    int left = 0;
    int maxArea = 0;

    while(left < right){

        //左边为比较短
        if(height[left] < height[right]){

            int tmp = (right - left) * height[left];//计算当前容器的容积

            if(tmp > maxArea){        //是否大于已知最大值
                maxArea = tmp;
            }

            ++left;        //向中间收缩,以得到新的容器
        }

        //右边为比较短,操作和上面同理
        else{

            int tmp = (right - left) * height[right];

            if(tmp > maxArea){
                maxArea = tmp;
            }

            --right;
        }
    }

    return maxArea;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值