LeetCode探索之旅2(92)-11Container with most water

今天继续刷LeetCode,第11题,求最大的储水量。

分析:
方法一:简单粗暴,通过两层循环,找到两根柱子之间的最小值,然后求面积,并输出面积的最大值;
方法二:双指针法,减少比较次数,通过一次遍历找到面积的最大值。

问题:

附上C++代码1:

class Solution {
public:
    int maxArea(vector<int>& height) {
        int max_contain=0;
        int min_len,s;
        for(int i=0;i<height.size();i++)
            for(int j=i+1;j<height.size();j++)
            {
                min_len=min(height[i],height[j]);
                s=min_len*(j-i);
                max_contain=max(max_contain,s);
            }
        return max_contain;
    }
};

附上C++代码2:

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

附上Python代码:

class Solution:
    def maxArea(self, height: List[int]) -> int:
        l=0
        r=len(height)-1
        max_area=0
        while l<r:
            max_area=max(max_area,(r-l)*min(height[r],height[l]))
            if height[r]>height[l]:
                l+=1
            else:
                r-=1
        return max_area
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值