[Leetcode]水最大容器


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,ai)处的点。 绘制n条垂直线,使得线i的两个端点位于(i,ai)和(i,0)。 找到两条线,它们与x轴一起形成一个容器,这样容器就含有最多的水。

一.穷举法

需要循坏两个列表长度,时间复杂度大

class Solution:
def maxArea(self, height):
    """
    :type height: List[int]
    :rtype: int
    """
    length=len(height)
    mian=[]
    while length>1:
        for i in range(length-1):

            minhei=min(height[0],height[i+1])
            mianji=minhei*(i+1)
            mian.append(mianji)
            resule=max(mian)

        height.pop(0)
        length=length-1
    return resule

clasee=Solution()
t=clasee.maxArea([1,8,6,2,5,4,8,3,7])
print(t)

二.(改进)

先计算最远处两根之间的面积,然后较短的一根往里面,这样可以保证虽然距离缩小但是面积不一定缩小,长的一根永远在

class Solution:
def maxArea(self, height):
    """
    :type height: List[int]
    :rtype: int
    """
    length=(len(height))
    i=0
    j=length-1
    result=0
    for n in range((length-1)):
        chang=min(height[i],height[j])
        mianji=chang*(j-i)
        result=max(mianji,result)

        if height[i]<height[j]:
            i=i+1
        else:
            j=j-1
    return result