leetcode刷题记录-11. 盛最多水的容器

刚开始用暴力循环

class Solution:
    def maxArea(self, height: List[int]) -> int:
        n=len(height)
        area=[]
        for x1 in range(n):
            for x2 in range(x1+1,n):
                width_rec= x2-x1 
                if height[x1]>height[x2]:
                    height_rec= height[x2]
                else:
                    height_rec= height[x1]
                # 
                area.append(width_rec*height_rec)return max(area)

会超时,看了题解是要用双指针的方法,从两边开始移动,现在时间比较紧,晚点自己写一遍原理证明,加强印象。

官方题解

class Solution:
    def maxArea(self, height: List[int]) -> int:
        l, r = 0, len(height) - 1
        ans = 0
        while l < r:
            area = min(height[l], height[r]) * (r - l)
            ans = max(ans, area)
            if height[l] <= height[r]:
                l += 1
            else:
                r -= 1
        return ans


作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/container-with-most-water/solution/sheng-zui-duo-shui-de-rong-qi-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值