题目描述:
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