Container With Most Water

Posted Peyton_Li

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Container With Most Water相关的知识,希望对你有一定的参考价值。

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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.

 

分析:

方法一:使用最简单的嵌套循环遍历,找出每一种组合。但此方法超时

方法二:容器的盛水量取决于两块板中的最短板,所以两个指针,一头一尾,记录其盛水量,然后向中间移动其较短的板,期间记录最大盛水量,直至两个指针相遇。这样时间复杂度就由方法一的O(N2)变为了O(N)。使用两个指针,一头一尾的方法很值得借鉴。

class Solution(object):
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        n = len(height)
        i = 0
        j = n-1
        max_area = 0
        while(i<j):
            if height[i] < height[j]:
                area = (j-i)*height[i]
                i += 1
            else:
                area = (j-i)*height[j]
                j -= 1
            if area > max_area:
                max_area = area
        return max_area

 

以上是关于Container With Most Water的主要内容,如果未能解决你的问题,请参考以下文章

11 Container With Most Water

LeetCode11-Container With Most Water

LeetCode11. Container With Most Water 解题报告

Container with most water

Container With Most Water

Container With Most Water