【优选算法】盛最多水的容器(双指针算法)

 11. 盛最多水的容器 - 力扣(LeetCode)

【1.题目】

【2.算法原理】

【3.代码编写】

优化之后就遍历了一遍数组,时间复杂度变为O(N),就使用了几个变量,空间复杂度为O(1)。

class Solution 
{
public:
    int maxArea(vector<int>& height) 
    {
        int left = 0,right = height.size()-1,ret=0;
        while(left<right)
        {
            int v = min(height[left],height[right])*(right-left);
            ret = max(ret,v);
            if(height[left]<height[right]) left++;
            else right--;
        }
        return ret;
    }
};

下面是我自己一开始写的,虽然也通过了,但,采九朵莲 !

class Solution 
{
public:
    int maxArea(vector<int>& height) 
    {
        int left = 0;
        int right =height.size()-1;
        int small = height[left];
        if(height[left]>height[right])
        {
            small = height[right];
        }
        int v = small*(right-left);
        int max = v;
        while(left < right)
        {
            //谁小谁移动
            if(height[left]<height[right])
                left++;
            else
                right--;

            //算新的体积
            int small2 = height[left];
            if(height[left]>height[right])
            {
                small2 = height[right];
            }
            v = small2*(right-left);

            //更新max
            if(max<v)
                max=v;
        }
        return max;
    }
};  

有思路的同时要一定考虑时间和空间复杂度,提醒自己学习完算法之后也要多回顾,真正学习到其中的妙处,然后为自己所用。

完——


评论 46
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

云边有个稻草人

您的鼓励是我最大的动力,感谢

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

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

打赏作者

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

抵扣说明:

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

余额充值