栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/629899.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号