LeetCode-11 - 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.

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.
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 我们已经认识14年了,分分合合我们走到了今天,我感觉走不下去了,不是我的猜疑我就是觉得你我之间没有了爱得感觉。我们...
    亲爱的小仙阅读 521评论 0 4
  • 实际上,煮溏心蛋并不是一件容易的事情,因为鸡蛋里的蛋黄和蛋清对于加热温度是非常敏感的。鸡蛋中的蛋清对蛋黄起到缓冲保...
    言射手阅读 200评论 0 4
  • 有没有发觉自己喜欢停留在一个思维的“舒适区”里,虽觉无聊但日子也算过得去?没事时掏出手机刷下微博,看下朋友圈,玩会...
    蓝菲杰阅读 1,150评论 5 14
  • 两家子彼此认承后,张老善人愈发催二孙子上上心,他二孙子懂得可怜天下爷奶心,不再生爷爷的气,本来也是二人情感发...
    豫兰剑客阅读 389评论 0 0
  • 新海阳、新感觉 (2012-03-25 17:30:58)转载 标签: 杂谈 检查工作已过大半,午饭后来到了海阳凤...
    田园牧歌123阅读 163评论 0 0