Leetcode题解-11. Container With Most Water

Leetcode题解-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 and n is at least 2.

思路

  一种简单的想法就是用两重遍历,那时间复杂度就是O(n^2)了,比较简单这里就不再赘述了。
  这里用另外一种方法:用max表示最大容量,开始时用i指向数组头,j指向数组尾,求出i、j之间的容量min{height[i], height[j]}·(j-i),与max比较,max比当前所求容量小则将当前容量赋值给max。然后倘若height[i]小于height[j],则i++,反之j- -。重复上述过程直至i等于j,返回max。这里时间复杂度为O(n).
  证明:假设height[i] < height[j],container1 =height[i]·(j-i),则container1 > container2(container2 = height[k]·(k-i)(i < k < j)),所以不必要考虑container2,所以将i++。反之height[i] > height[j]同样的道理,只需要将j- -。

代码

int maxArea(vector<int>& height) {
        int i = 0, j = height.size() - 1;
        int max = 0;
        while(i != j){
            int min = 0;
            int cur = 0;
            if(height[i] <= height[j]){
                min = height[i];
                cur = min * (j-i);
                i++;
            }
            else{
                min = height[j];
                cur = min * (j-i);
                j--;
            }
            if(max < cur) max = cur;
        }
        return max;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值