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)