11. 盛最多水的容器
- 题号:11
- 来源:LeetCode
- 难度:中等
- 标签:
双指针贪心数组 - 语言:TypeScript · Python
- 解法:2 个
- 作者:lmliheng
- 最近更新:2026-09-29
TypeScript
TypeScript · O(n) 时间 · O(1) 空间 · 更新于 2026-09-27
双指针从两端收缩,每次移动较短的一边
typescript
/**
* @difficulty medium
* @tags 双指针,贪心,数组
* @time O(n)
* @space O(1)
* @note 双指针从两端收缩,每次移动较短的一边
* @11. 盛最多水的容器
*/
function maxArea(height: number[]) {
let head = 0;
let foot = height.length - 1;
let maxArea = 0;
while (head < foot) {
const area = Math.min(height[head], height[foot]) * (foot - head);
maxArea = Math.max(maxArea, area);
if (height[head] < height[foot]) {
head++;
} else {
foot--;
}
}
return maxArea;
};Python
Python · O(n) 时间 · O(1) 空间 · 更新于 2026-09-29
双指针向中间收,移动较短的一边
python
"""
@difficulty medium
@tags 双指针,贪心
@time O(n)
@space O(1)
@note 双指针向中间收,移动较短的一边
盛最多水的容器
lc 11
题目中heigtht[left]<height[right],必然有
aera(left,right)>aera(left,right-1)
所以left必定要+1
"""
class Solution:
def maxArea(self, height: List[int]) -> int:
n = len(height)
left = 0
right = n - 1
res = 0
res = max(res, min(height[left], height[right]) * (right - left))
while left<right:
if height[left]<height[right]:
left+=1
else:
right-=1
res = max(res, min(height[left], height[right]) * (right - left))
return res源码:python/leetcode/hot100/5.py
在 GitHub 上查看题目所在目录:lmliheng/algorithm