LeetCode 题解工作台
盛最多水的容器
给定一个长度为 n 的整数数组 height 。有 n 条垂线,第 i 条线的两个端点是 (i, 0) 和 (i, height[i]) 。 找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。 返回容器可以储存的最大水量。 说明: 你不能倾斜容器。 示例 1: 输入: [1,8,6…
3
题型
10
代码语言
3
相关题
当前训练重点
中等 · 双·指针·invariant
答案摘要
我们使用两个指针 和 分别指向数组的左右两端,即 $l = 0$,而 $r = n - 1$,其中 是数组的长度。 接下来,我们使用变量 记录容器的最大容量,初始化为 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路
题目描述
给定一个长度为 n 的整数数组 height 。有 n 条垂线,第 i 条线的两个端点是 (i, 0) 和 (i, height[i]) 。
找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
返回容器可以储存的最大水量。
说明:你不能倾斜容器。
示例 1:

输入:[1,8,6,2,5,4,8,3,7] 输出:49 解释:图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。
示例 2:
输入:height = [1,1] 输出:1
提示:
n == height.length2 <= n <= 1050 <= height[i] <= 104
解题思路
方法一:双指针
我们使用两个指针 和 分别指向数组的左右两端,即 ,而 ,其中 是数组的长度。
接下来,我们使用变量 记录容器的最大容量,初始化为 。
然后,我们开始进行循环,每次循环中,我们计算当前容器的容量,即 ,并将其与 进行比较,将较大值赋给 。然后,我们判断 和 的大小,如果 ,移动 指针不会使得结果变得更好,因为容器的高度由较短的那根垂直线决定,所以我们移动 指针。反之,我们移动 指针。
遍历结束后,返回 即可。
时间复杂度 ,其中 是数组 的长度。空间复杂度 。
class Solution:
def maxArea(self, height: List[int]) -> int:
l, r = 0, len(height) - 1
ans = 0
while l < r:
t = min(height[l], height[r]) * (r - l)
ans = max(ans, t)
if height[l] < height[r]:
l += 1
else:
r -= 1
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Do you understand the two-pointer technique and how it helps reduce the time complexity of this problem?
- question_mark
Can you explain why we always move the pointer pointing to the shorter line in the two-pointer approach?
- question_mark
Will you be able to implement the solution in linear time instead of simulating all possible pairs?
常见陷阱
外企场景- error
Failing to optimize the solution and instead using a brute-force approach that simulates all pairs, leading to O(n^2) time complexity.
- error
Incorrectly assuming that we need to calculate the area for every possible pair, without leveraging the two-pointer approach for optimization.
- error
Not updating the maximum area correctly when adjusting the pointers, potentially missing a larger valid container.
进阶变体
外企场景- arrow_right_alt
What if the problem includes additional constraints, such as a limit on the number of lines that can be considered for the container?
- arrow_right_alt
How would the solution change if the array elements were not restricted to heights, but had varying widths?
- arrow_right_alt
What if you need to find the maximum area of water contained between two specific indices, instead of any two lines?