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)
相关推荐
ん贤3 分钟前
单调栈详解【C/C++】
数据结构·c++·算法·贪心算法·单调栈
空雲.18 分钟前
ABC 373
算法·深度优先
舊時王謝堂前燕18 分钟前
macOS使用brew切换Python版本【超详细图解】
python·macos
点云登山者1 小时前
登山第二十梯:无人机实时自主探索——我是一只小小小鸟
算法·计算机视觉·机器人·无人机·路径规划·激光点云·自主探索
大胆飞猪1 小时前
优选算法训练篇08--力扣15.三数之和(难度中等)
算法·leetcode
yukai080081 小时前
【最后203篇系列】021 Q201再计划
python
battlestar2 小时前
Siemens Smart 200 PLC 通讯(基于python-)
前端·网络·python
人类群星闪耀时2 小时前
回溯法经典练习:组合总和的深度解析与实战
开发语言·python
时光呢2 小时前
JAVA泛型的作用
java·windows·python
夏莉莉iy2 小时前
[CVPR 2025]Neuro-3D: Towards 3D Visual Decoding from EEG Signals
人工智能·python·深度学习·神经网络·机器学习·3d·线性回归