題目描述:
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.
大意爲:給定n個數的數組a1,a2,…,an,在座標軸上表示點(i,a1)。以這n個點分別作x軸的垂線,起點和終點爲(i,ai)和(i,0)。求由其中兩條直線與x軸組成的容器,使得這個容器的盛水量最大。
分析:
每個容器盛水量取決於兩條邊的較短邊和兩條邊在x軸上的距離。使用暴力方法可以遍歷每一條邊(由第二條開始),然後依次往回計算其與前面每條邊的盛水量,再與當前盛水量的最大值比較。該算法複雜度爲O(n^2)。
但是暴力方法中包含了許多無用的計算。當一條短邊找到一條 比它高 且x軸距離最遠的邊,即可確定包含這條短邊的最大容水量。首先要滿足x軸距離最大,那麼我們可以設置兩個指針,分別指向這個數組的頭和尾,這時我們可以找到頭尾指針指中較短邊的最大容水量。如果是頭指針指向較短邊,則頭指針+1,因爲頭指針指向的邊能盛水的最大容量已經求出來了;否則尾指針-1。直到頭指針和尾指針相等即可跳出循環。該方法的時間複雜度爲O(n)。
代碼如下:
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
max_water=0
x=0
y=len(height)-1
while x<y:
water=0
if height[y]>=height[x]:
water=(y-x)*height[x]
x+=1
else:
water=(y-x)*height[y]
y-=1
max_water=max(max_water,water)
return max_water