題目:
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