leetcode 11 -- Container With Most Water

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.


题意:
给于一个序列,序列里面的数字代表高度,数字下标之差作为底边,两个高度之间能当作容器装水且装水量取决与两者较低值和两者在序列中的下标之差。


思路:
1.最普通的暴力求解法,但是测试时显示超时了,O(n^2)
2.类似贪心的算法,取左边界和右边界,计算,然后每次选取较低的高度的下标推进,从而保留高的下标记,保证下一次我们可能选取到较优的解。比如,cont = min(a[i],a[j])*(j-i) and i < j, 如果a[i] < a[j],那么=>i++,因为i++j--容器底边都是减1,而我们保留高度高的a[j],下一次计算时肯定会比执行j--的容量大。也就是每次尽量向更优的解去移动,至于有些没移动到的范围是因为我们在判断时(如上面的例子)就把它pass掉了,时间复杂度O(n)


代码:

class Solution {
public:
    typedef vector<int>::iterator vter;
    int maxArea(vector<int>& height) {
        auto left = height.begin();
        auto right = height.end()-1;
        int max = 0;
        while(left != right){
            vter tmp = min(left, right);
            int val = (right-left)*(*min(left, right));
            if(max < val){
                max = val;
            }
            if(tmp == left){
                ++left;
            }else{
                --right;
            }
        }
        return max;
    }
    vter min(vter a, vter b){
        return *a < *b ? a : b;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

夏天的技术博客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值