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 line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container and n is at least 2.
![](https://img.haomeiwen.com/i18705940/6bff4886efe0cb7f.jpg)
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:
Input: [1,8,6,2,5,4,8,3,7]
Output: 49
思路
- 暴力遍历,依次遍历容器的左右边界,以左右边界中高度较小的当做容器高度,计算面积。
# 1. 使用暴力搜索,时间复杂度为O(n**2)
def maxArea(self, height: List[int]) -> int:
max_area = 0
for i in range(0, len(height) - 1):
for j in range(i + 1, len(height)):
area = (j - i) * min(height[i], height[j])
max_area = max(area, max_area)
return max_area
- 双指针法, 先以数组的最左最右当做容器的左右边界,再向中间收敛。因为从数组两端开始已经保证了容器的最宽宽度,现在要找更高的高度,如果左边界高度小于右边界,则左边界向里移动,否则右边界向内移动。
# 2. 双指针,向内收敛,时间复杂度为O(n)
def maxArea2(self, height: List[int]) -> int:
l, r = 0, len(height) - 1
max_area = 0
while (l < r):
area = (r - l) * min(height[l], height[r])
max_area = max(max_area, area)
if height[l] < height[r]:
l += 1
else:
r -= 1
return max_area
网友评论