Leetcodeleetcode

11. Container With Most Water

2017-10-26  本文已影响7人  ciantian

最近再刷leetcode,除了链表之外的都用python 实现,贴出一些代码,希望指正.

问题描述:

原文中说了大堆,用下面这幅图演示.
输入是一串坐标,然后随便两个和x轴连线之间构成一个面积,要求的是最大的面积.


11_Container_Water.gif

解决思路

分别从两边同时向中间遍历,比较坐标值,小的向里缩之后重合,每次计算大小之前先求面积,迭代出最大的一个.输出.

class Solution(object):
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        # print(height)
        area_max = 0
        i = 0
        j = len(height) - 1
        while i != j:
            tmp_max = (j - i) * min(height[i], height[j])
            area_max = max(tmp_max, area_max)
            if height[i] < height[j]:
                i = i + 1
            else:
                j = j - 1
        return area_max
solution = Solution()
list1 = [3, 2, 5, 7, 3, 5]
print(solution.maxArea(list1))
上一篇 下一篇

猜你喜欢

热点阅读