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.
Example: Input: [1,8,6,2,5,4,8,3,7] Output: 49
思路
我们可以设置两个指针,一个指向开始位置,一个指向尾部。然后求出当前储水量,然后将短的一方向前移动,然后继续算储水量。并且和之前的进行比较。大于替换,否则直接下一步。 时间复杂度O(n), 空间复杂度为O(1)。
图示步骤
代码
1 class Solution(object):
2 def maxArea(self, height):
3 if len(height) < 2: # 长度小于2直接返回
4 return 0
5 start, end = 0, len(height)-1
6 areas = 0
7 while start < end: # 开始循环比较
8 tem = min(height[start], height[end]) # 选出最小的数字
9 areas = max(areas, tem*(end - start)) # 与之前的储水量进行比较
10 if height[start] < height[end]: # 选择移动的指标
11 start += 1
12 else:
13 end -= 1
14 return areas