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)
相关推荐
databook1 小时前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室2 小时前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三3 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
用户2519162427117 小时前
Python之语言特点
python
刘立军7 小时前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
聚客AI9 小时前
🙋‍♀️Transformer训练与推理全流程:从输入处理到输出生成
人工智能·算法·llm
数据智能老司机10 小时前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
大怪v11 小时前
前端:人工智能?我也会啊!来个花活,😎😎😎“自动驾驶”整起!
前端·javascript·算法
数据智能老司机11 小时前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i13 小时前
django中的FBV 和 CBV
python·django