美文网首页LeetCode
LeetCode-11 - Container With Mos

LeetCode-11 - Container With Mos

作者: 空即是色即是色即是空 | 来源:发表于2017-11-15 13:42 被阅读6次

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.

Solution1

很容易想到的方法就是,每两个点之间作计算,最终找出最大值。
算法复杂度为O(n2)

class Solution(object):
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        mmax = 0
        for i in range(len(height)):
            for j in range(i + 1, len(height)):
               mmax = max(mmax, (j - i) * min(height[i], height[j]))
        return mmax

Solution2

抓住问题的本质,将问题简化,如下算法复杂度为O(n)

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

思路

  • The widest container (using first and last line) is a good candidate, because of its width. Its water level is the height of the smaller one of first and last line.
  • All other containers are less wide and thus would need a higher water level in order to hold more water.
  • The smaller one of first and last line doesn't support a higher water level and can thus be safely removed from further consideration.

相关文章

网友评论

    本文标题:LeetCode-11 - Container With Mos

    本文链接:https://www.haomeiwen.com/subject/ulicvxtx.html