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)
相关推荐
吴佳浩2 小时前
Python入门指南(六) - 搭建你的第一个YOLO检测API
人工智能·后端·python
superman超哥3 小时前
仓颉语言中基本数据类型的深度剖析与工程实践
c语言·开发语言·python·算法·仓颉
Learner__Q3 小时前
每天五分钟:滑动窗口-LeetCode高频题解析_day3
python·算法·leetcode
————A4 小时前
强化学习----->轨迹、回报、折扣因子和回合
人工智能·python
阿昭L4 小时前
leetcode链表相交
算法·leetcode·链表
闻缺陷则喜何志丹4 小时前
【计算几何】仿射变换与齐次矩阵
c++·数学·算法·矩阵·计算几何
liuyao_xianhui4 小时前
0~n-1中缺失的数字_优选算法(二分查找)
算法
徐先生 @_@|||4 小时前
(Wheel 格式) Python 的标准分发格式的生成规则规范
开发语言·python
Mqh1807624 小时前
day45 简单CNN
python
hmbbcsm4 小时前
python做题小记(八)
开发语言·c++·算法