题目:
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.
举例: Input: [1,8,6,2,5,4,8,3,7] Output: 49
题目分析:
首先最先想到的是暴力法。遍历所有组合,求出最大值。
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
maxvalue = 0
for i in range(len(height)):
for j in range(i+1,len(height)):
maxvalue = max( min(height[i], height[j]) * abs(i - j),maxvalue)
return maxvalu
此方法复杂度O(n^2), 无法通过。
进而利用两端指针分析法,参考 https://blog.csdn.net/qq_36721548/article/details/80159570 , 即两个指针分别置于首位,如果保留较小的长度,则后续遍历的容器大小必然会小于当前值(宽度在减少);因而保留较大值,移动较小值的指针。同理类推至重合。保留过程中的最大值。算法复杂度仅为 O(n)。(runtime 36 ms)
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
i,j,area = 0, len(height)-1, 0
while i<=j:
if height[i] > height[j]:
h = height[j]*(j-i)
j -= 1
else:
h = height[i]*(j-i)
i += 1
area = max(area,h)
return area