LeetCode | 盛最多水的容器

557 字
3 分钟
LeetCode | 盛最多水的容器

分类:双指针 / 数组

题目#

给定一个整数数组 height,数组中的每个数字表示一条竖线的高度。

任意选择两条竖线,它们和 x 轴可以组成一个容器。

求能够装下的最大水量。

盛最多水的容器示例
盛最多水的容器示例

示例:

输入:height = [1,8,6,2,5,4,8,3,7]
输出:49

讲解#

容器能装多少水,取决于:

宽度 = 两条线之间的距离
高度 = 两条线中较短的那条
面积 = 宽度 * 高度

暴力做法是枚举所有两条线的组合,计算每一对的面积。这样可以得到答案,但是有两层循环,时间复杂度是 O(n^2)

这道题可以用双指针。先让 left 指向最左边,right 指向最右边。

当前面积是:

(right - left) * min(height[left], height[right])

接下来应该移动较短的那一边。

原因是:如果固定较短的那条线,只移动较高的那条线,宽度一定变小,而容器高度仍然不会超过原来的短板,所以面积不可能变大。

笔者的小巧思: 代码在这个基础上又做了一步剪枝:移动短板之后,如果新的高度还比刚才的短板更矮,就继续跳过。因为宽度已经变小,高度还更矮,这种位置也不可能得到更大的面积。

复杂度#

  • 暴力做法:
    • 时间复杂度:O(n^2)
    • 空间复杂度:O(1)
  • 双指针做法:
    • 时间复杂度:O(n)
    • 空间复杂度:O(1)

每个指针只会向中间移动,不会回头,所以总移动次数最多是 n 次。

代码#

源码#

from typing import List
class Solution:
def maxArea(self, height: List[int]) -> int:
left = 0
right = len(height) - 1
ans = 0
while left < right:
if height[right] < height[left]:
h = height[right]
area = (right - left) * h
if area > ans:
ans = area
right -= 1
while left < right and height[right] < h:
right -= 1
else:
h = height[left]
area = (right - left) * h
if area > ans:
ans = area
left += 1
while left < right and height[left] < h:
left += 1
return ans

测试#

from src.python._011_Container_With_Most_Water import Solution
sol = Solution()
assert sol.maxArea([1, 8, 6, 2, 5, 4, 8, 3, 7]) == 49
assert sol.maxArea([1, 1]) == 1
assert sol.maxArea([4, 3, 2, 1, 4]) == 16
print("PASS")

参考资料#

文章分享

如果这篇文章对你有帮助,欢迎分享给更多人!

LeetCode | 盛最多水的容器
https://leetcode.cn/problems/container-with-most-water/
作者
平昊阳
发布于
2026-08-02
许可协议
CC BY-NC-SA 4.0

评论区

Profile Image of the Author
平昊阳
乘长风,破巨浪, 展鸿图于未央!
--
总访问量
--
访客数
公告
欢迎来到我的个人博客!欢迎关注交流吖!
更多相关公告,见
社交-留言」。
音乐
封面

音乐

暂未播放

0:000:00
暂无歌词
站点统计
文章
66
分类
16
标签
93
总字数
477,284
运行时长
0
最后活动
0 天前

文章目录