Container With Most Water 解题教学:3 种解法完整比较|LeetCode 11 Best Practice

Container With Most Water 解题教学示意图|LeetCode 11

本文完整拆解LeetCode 11 Container With Most Water 的解法:从解题思路、演算法步骤到时间与空间复杂度,并整理边界情况与3 种解法比较,帮你把Container With Most Water 一次弄懂。

Explore diverse LeetCode solutions in Python, C++, JavaScript, SQL, and TypeScript. Ideal for interview prep, learning, and code practice in multiple programming languages. Github Repo Link


You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the i th line are (i, 0) and (i, height[i]).

Find two lines that together with the x-axis form a container, such that the container contains the most water.

Return the maximum amount of water a container can store.

Notice that you may not slant the container.

Example 1:

Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

Example 2:

Input: height = [1,1]
Output: 1

Constraints:

  • n == height.length
  • 2 <= n <= 10 5
  • 0 <= height[i] <= 10 4

Python

				
					from typing import List class Solution: def maxArea(self, height: List[int]) -> int: maxSum = 0 left, right = 0, len(height) - 1 while left < right: maxSum = max(maxSum, ( right - left) * min(height[left], height[right])) if height[left] < height[right]: left += 1 else: right -= 1 return maxSum Height = [1, 8, 6, 2, 5, 4, 8, 3, 7] print(Solution().maxArea(Height))
				
			

Container With Most Water 解题思路

容器的容量等于「较矮的那根柱子高度」乘上「两根柱子的距离」。从最宽的两端开始夹逼,每次移动都会让宽度变小,所以唯一可能把面积变大的做法,就是放弃较矮的那一边去换更高的柱子——移动较高的那边只会让面积更小,可以安全排除。

Container With Most Water 演算法步骤

  1. 左指针放在索引0,右指针放在最后一格。
  2. 计算目前面积= min(height[left], height[right]) * (right – left),更新最大值。
  3. 若height[left] 小于height[right],把left 往右移一格。
  4. 否则把right 往左移一格,重复直到两指针相遇。

Container With Most Water 复杂度分析

项目复杂度
时间复杂度O(n)
空间复杂度O(1)

两个指针合计只走访阵列一次,时间为O(n)。只用到几个纯量变数,空间O(1)。这题的价值在于理解「为什么移动较高的一边不可能更好」这个排除论证。

Container With Most Water 的边界情况与常见错误

  • 阵列长度小于2 时没有容器,答案为0。
  • 两边高度相同时移动任一边都可以,但必须移动其中一边以免无穷回圈。
  • 高度为0 的柱子要正常参与计算,不需要特判。
  • 面积可能很大,注意相乘后的数值范围。

Container With Most Water 其他解法比较

解法时间空间说明
双层回圈列举所有配对O(n²)O(1)最直觉,n 大就超时
单调堆叠O(n)O(n)可行但对本题过度设计
左右双指针夹逼O(n)O(1)本文采用,最佳解