11. 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.

Note: You may not slant the container.

题目大意:(i,ai)表示在位置i线的高度,求两条线中间最大的存水量(假设为存水)。根据木桶原理,容量=最矮的高度*距离

方法:不能用穷举法,时间复杂度太高。两边分别设置一个指针,一左一右逐渐向中间移动指针。比较两个指针高度,高度小的向中间移动,比较移动后和移动前容量大小,得到最大存水量。

public class Solution {
    public int maxArea(int[] h) {
        if(h==null || h.length==0) return 0;

        int left=0,right=h.length-1;
        int area=0;
        while(left<right){
            area=Math.max(area,(right-left)*Math.min(h[left],h[right]));//获取最大容量
            if(h[right]>h[left]){
               left++;
            }else{
               right--;
            }
        }
        return area;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值