题目
11. 盛最多水的容器
给定一个长度为 n 的整数数组 height 。有 n 条垂线,第 i 条线的两个端点是 (i, 0) 和 (i, height[i]) 。
找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
返回容器可以储存的最大水量。
说明:你不能倾斜容器。
我的代码(Python)
class Solution:
def maxArea(self, height: List[int]) -> int:
left = 0
right = len(height) - 1
currMax = 0
while left < right:
currMax = max(currMax, min(height[right], height[left]) * (right - left))
if height[left] < height[right]:
currLeft = height[left]
while height[left] <= currLeft and left < right:
left += 1
else:
currRight = height[right]
while height[right] <= currRight and left < right:
right -= 1
return currMax
点评
做过的题目,印象比较深,还记得解法,所以思路没问题。
和官方解答相比,在双指针移动时多了些比较,减少了计算过程,算是有一点优化。