Leetcode题库——11.盛最多水的容器


@author: ZZQ
@software: PyCharm
@file: maxArea.py
@time: 2018/10/11 21:47
说明:给定 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
示例: 输入: [1,8,6,2,5,4,8,3,7]
输出: 49
思路:两个指针分别指向首尾,当满足 first < last时,计算面积,并判断首尾指针指向的高度哪个大,较小的一端移动指针。

class Solution(object):
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        first = 0
        last = len(height)-1
        area = 0
        while first < last:
            area = max(area, min(height[first], height[last])*(last-first))
            if height[last] > height[first]:
                first += 1
            else:
                last -= 1
        return area
if __name__ == "__main__":
    answer = Solution()
    print(answer.maxArea([1, 8, 6, 2, 5, 4, 8, 3, 7]))
原文地址:https://www.cnblogs.com/zzq-123456/p/9787758.html