Leetcode 11. Container With Most Water

如何盛最大的水?
数组代表高度, 盛的水量V= min( height[left] 、 height[right] ) * 底部的长度= [right- left]
双指针解决这个问题, 从左边、右边不断逼近, 逐渐取得最大值,

如何进行更新, 不断进行更新逼近,因为决定的是height[left]、height[right],中的最小值, 所以当,对right 和height 采用快速排序中不断毕竟的原则

答案是有,用两个指针从两端开始向中间靠拢,如果左端线段短于右端,那么左端右移,反之右端左移,知道左右两端移到中间重合,记录这个过程中每一次组成木桶的容积,返回其中最大的。

英文解释该中情况

Start by evaluating the widest container, using the first and the last line. All other possible containers are less wide, so to hold more water, they need to be higher. Thus, after evaluating that widest container, skip lines at both ends that don’t support a higher height. Then evaluate that new container we arrived at. Repeat until there are no more possible containers left.
快速排序

class Solution {
    public int maxArea(int[] heights) {
       int result=0;
        int n = heights.length;
        int left=0, right =n-1;
        while(left<right){
            int tmp= (right-left) * Math.min(heights[left],heights[right]);
            result = Math.max(tmp,result);
            if(heights[left]<heights[right])
            {
                ++left;
            }
            else
            {
                --right;
            }
        }
        return result;
    }
}

如何进行改进

int maxArea(vector<int>& height) {
    int water = 0;
    int i = 0, j = height.size() - 1;
    while (i < j) {
        int h = min(height[i], height[j]);
        water = max(water, (j - i) * h);
        //i<j 必须满足该中情况, 类似快速排序
        while (height[i] <= h && i < j) i++;
        
        while (height[j] <= h && i < j) j--;
    }
    return water;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值