leetcode [array] Container With Most Water

题目:
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.

题目翻译:
给定a1,a2,……,an的n个非负整数,它们构成一个数组,其中每一个下标对应的(i,0)和(i,ai)构成一条垂直于x轴的垂直线。现取两条垂直线和x轴构成一个容器,问,容器最多能乘多少水?

题解:
思路一:暴力法(双重遍历法)
刚开始写时,没有多想直接用了暴力的方法,即双重循环比较找出最大的容量,提交后就TLE了,此方法不再次列出。

思路二:双指针
因为第一种方法超时,显然是因为不是所有的情况都需要遍历,即,部分情况可以不用考虑。

若有一个容器,它的容量取决于底和两边高中较短的一边的长度。现在从底最大的长度开始遍历,即left=0,right=n-1,假设左边比右边高,若将left+1,则移动后有3种情况:
1、a[left]>a[right],由于移动前左边高,而现在的高度为右边,故高度减少,底长也减少,总容量减少;
2、a[left]=a[right],高度不变,但底减少,故总容量还是减少;
3、a[left]< a[right],移动前左边比右边高,容器的高是右边,移动后左边比右边低,容器的高是左边,高减少,底减少,故容器总容量减少。

通过上面的分析得,移动较高的一边时,容器总量一定减少,故为了得到最大值,只将较小的一边移动即可。

解答如下:

class Solution(object):
    def maxArea(self, height):
        n=len(height)
        left=0
        right=n-1
        max_num=0
        while left<right:
            max_num=max(max_num,min(height[left],height[right])*(right-left))
            if height[left]<height[right]:
                left=left+1
            else:
                right=right-1
        return max_num
#下面两行是测试用,提交时不用加这两行
height=[8,1,3,5,7]
print(Solution().maxArea(height))

猜你喜欢

转载自blog.csdn.net/shu_xi/article/details/80055724