LeetCode

LeetCode-11 - Container With Mos

2017-11-15  本文已影响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

思路

上一篇 下一篇

猜你喜欢

热点阅读