11.盛最多水的容器--python

题目:给定height中每个数代表一条竖线的高度,找出height中两条线,使得它们与x轴共同构成的容器可以容纳最多的水

法:左右指针,只是移动左右指针的条件有点特别,比较height[left]与height[right]的大小,如果height[left]是较小的那条线,使得left+=1,因为此时height[left]相当于是“短板”,考虑left后的数可能会获取更大的值

def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        left,right=0,len(height)-1
        res=(right-left)*min(height[left],height[right])
        while left<right:
            if height[right]<height[left]:
                right-=1
            else:
                left+=1
            res=max(res,(right-left)*min(height[left],height[right]))
        return res

猜你喜欢

转载自blog.csdn.net/karen17/article/details/88880922