美文网首页
11. 盛水最多的容器

11. 盛水最多的容器

作者: oneoverzero | 来源:发表于2020-01-28 10:52 被阅读0次

题目描述:

给定 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。

说明:你不能倾斜容器,且 n 的值至少为 2。

代码:

class Solution(object):
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        if len(height) < 2:
            return None
        res = 0
        lo, hi = 0, len(height)-1
        while lo < hi:
            res = max(res, min(height[lo],height[hi])*(hi-lo))
            if height[lo] < height[hi]:
                k = lo
                while k < hi and height[k] <= height[lo]: # 这里必须是小于等于号,
                    k += 1
                lo = k
            else:
                k = hi
                while k > lo and height[k] <= height[hi]: # 否则会引起死循环
                    k -= 1
                hi = k
        return res

思路分析:

参见: https://blog.csdn.net/a83610312/article/details/8548519

时间复杂度:O(n)

相关文章

网友评论

      本文标题:11. 盛水最多的容器

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