leetcode_双指针 11. 盛最多水的容器

11. 盛最多水的容器

  • 给定一个长度为 n 的整数数组 height 。有 n 条垂线,第 i 条线的两个端点是 (i, 0) 和 (i, height[i]) 。

  • 找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。

  • 返回容器可以储存的最大水量。

  • 说明:你不能倾斜容器。

1. 双重循环(记录用)

bash 复制代码
class Solution(object):
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        res = []
        for left in range(len(height)):
            for right in range(left, len(height)):
                a = right - left
                b = min(height[left], height[right])
                s = a * b
                res.append(s)

        return max(res)
  • 时间复杂度: O(n^2)
  • 空间复杂度: O(n^2)

2. 双指针

  • 使用对向双指针来优化时间复杂度,一个指向数组的开头(left),另一个指向数组的末尾(right),当两个指针相遇时,循环停止。
bash 复制代码
class Solution(object):
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        max_area = 0
        left, right = 0, len(height) - 1 # 对向双指针
        
        while left < right:
            current_area = (right - left) * min(height[left], height[right])  # 计算当前容器的容量
            max_area = max(max_area, current_area)  # 更新最大容量
            
            # 移动较短的那条线段的指针
            if height[left] < height[right]:
                left += 1
            else:
                right -= 1
                
        return max_area
  • 时间复杂度: O(n),只需遍历数组一次
  • 空间复杂度: O(1)
相关推荐
hn小菜鸡1 小时前
LeetCode 377.组合总和IV
数据结构·算法·leetcode
Deepoch2 小时前
Deepoc 大模型:无人机行业的智能变革引擎
人工智能·科技·算法·ai·动态规划·无人机
天真小巫2 小时前
2025.6.27总结
职场和发展
费弗里3 小时前
Python全栈应用开发利器Dash 3.x新版本介绍(1)
python·dash
李少兄9 天前
解决OSS存储桶未创建导致的XML错误
xml·开发语言·python
就叫飞六吧9 天前
基于keepalived、vip实现高可用nginx (centos)
python·nginx·centos
Vertira9 天前
PyTorch中的permute, transpose, view, reshape和flatten函数详解(已解决)
人工智能·pytorch·python
heimeiyingwang9 天前
【深度学习加速探秘】Winograd 卷积算法:让计算效率 “飞” 起来
人工智能·深度学习·算法
学Linux的语莫9 天前
python基础语法
开发语言·python
匿名的魔术师9 天前
实验问题记录:PyTorch Tensor 也会出现 a = b 赋值后,修改 a 会影响 b 的情况
人工智能·pytorch·python