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

盛水最多的容器 两种写法(Python)

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

盛水最多的容器 两种写法(Python)

LeetCode链接

穷举法 时间复杂度O(N^2)

然而此方法会超时。。

class Solution:
    def maxArea(self, height: List[int]) -> int:
        max_area = 0
        for i in range(0, len(height) - 1):
            for j in range(i + 1, len(height)):
                max_area = max(max_area, (j - i) * min(height[i], height[j]))
        return max_area
双指针 左右夹逼 时间复杂度O(N)
class Solution:
    def maxArea(self, height: List[int]) -> int:
        l, r = 0, len(height) - 1
        max_area = 0
        # 全局最大高度
        max_h = max(height)
        while l < r:
            # 两边夹逼 宽度越来越小 
            # 如果配合全局最大的高度都无法超过 当前的最大结果,则再往内也不会有更大的了
            if max_h * (r - l) < max_area:
                break
            max_area = max(max_area, (r - l) * min(height[r], height[l]))
            if height[l] < height[r]:
                l += 1
            else:
                r -= 1
        return max_area
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/853249.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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