原题链接:Container With Most Water - LeetCode
题目
Given n
non-negative integers a1, a2, ..., an
, where each represents a point at coordinate (i, ai)
. n
vertical lines are drawn such that the two endpoints of the line i
is at (i, ai)
and (i, 0)
. Find two lines, which, together with the x-axis forms a container, such that the container contains the most water.
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
Example 3:
Input: height = [4,3,2,1,4]
Output: 16
Example 4:
Input: height = [1,2,1]
Output: 2
Constraints:
n == height.length
2 <= n <= 105
0 <= height[i] <= 104
解法1
首先能想到的是,这里的容器水面积等于长度*宽度,宽度是两条线之间距离(j-i),高度是两条线中短线的高度(min(height[i], height[j]))。
遍历每两条线可以暴力破解这道题,但是时间复杂度为O(n^2)。
解法2
可以观察到,如果从两边的线开始向内移动的话,因为宽度在变小,唯一可能让面积更大的是让高度更高。而短线和任意一条线组成容器的高度都不可能让高度更高,所以让指向短线的指针向内移动。
举个例子来说,如果height[i] < height[j],那么对于i和j之间的任意下标k,min(height[i], height[k]) <= height[i]都成立,所以i和k组成的面积不可能大于i和j组成的容器,即min(height[i], height[k])*(j-k) <= height[i]*(j-i)。这时可以将i加1来略过这些无用的组合。
这种解法的时间复杂度为O(n)。
class Solution:
def maxArea(self, height: List[int]) -> int:
i, j = 0, len(height) - 1
max_area = 0
while i < j:
if height[i] < height[j]:
area = height[i] * (j - i)
i += 1
else:
area = height[j] * (j - i)
j -= 1
max_area = max(max_area, area)
return max_area
解法2优化
还有个很细节的点可以优化,就是当height[i] == height[j]时,可以同时让i加1和j减1。因为这时i和k组成的面积不可能大于i和j组成的容器,j和k组成的面积也不可能大于i和j组成的容器。
时间复杂度没有变,还是O(n)。
class Solution:
def maxArea(self, height: List[int]) -> int:
i, j = 0, len(height) - 1
max_area = 0
while i < j:
if height[i] < height[j]:
area = height[i] * (j - i)
i += 1
elif height[i] > height[j]:
area = height[j] * (j - i)
j -= 1
else:
area = height[j] * (j - i)
i += 1
j -= 1
max_area = max(max_area, area)
return max_area