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)
相关推荐
狐572 小时前
2026-01-22-LeetCode刷题笔记-3507-移除最小数对使数组有序I
笔记·leetcode
充值修改昵称2 小时前
数据结构基础:B树磁盘IO优化的数据结构艺术
数据结构·b树·python·算法
C系语言2 小时前
python用pip生成requirements.txt
开发语言·python·pip
william_djj2 小时前
python3.8 提取xlsx表格内容填入单个文件
windows·python·xlsx
kszlgy7 小时前
Day 52 神经网络调参指南
python
程序员-King.8 小时前
day158—回溯—全排列(LeetCode-46)
算法·leetcode·深度优先·回溯·递归
wrj的博客8 小时前
python环境安装
python·学习·环境配置
Pyeako8 小时前
深度学习--BP神经网络&梯度下降&损失函数
人工智能·python·深度学习·bp神经网络·损失函数·梯度下降·正则化惩罚
月挽清风9 小时前
代码随想录第七天:
数据结构·c++·算法
小O的算法实验室9 小时前
2026年AEI SCI1区TOP,基于改进 IRRT*-D* 算法的森林火灾救援场景下直升机轨迹规划,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进