Python习题——2018-04-23作业

11. Container With Most Water

题目链接:LeetCode #11

题目描述

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.

思路

最简单的思路是,固定a1,分别计算它与a2, …, an组成容器的容积,取最大值;之后固定a2,分别计算它与a3, …, an组成容器的容积,分别与先前求得的最大值进行比较,如果更大,则取代原最大值。一直这样做,直到将每两条线组成容器的容积计算一遍以后,得到的最大值就是题目要求的最大容积。这个算法的时间复杂度是 O ( n 2 )

除了从左到右遍历,还有其它的做法,例如从中间向两边分散,或者从两边向中间靠拢。考虑两边向中间靠拢的做法。设当前选择的边为ai和aj,其中i < j。不妨设ai < aj。容器的容积是容器的高度和容器的底的长度的乘积,其中容器的高度是左右两边中最短边的长度。现在向中间靠拢一步,那么应当移动ai而非aj。原因是如果移动aj,那么由ai < aj,移动后容器的高度将不会大于移动前容器的高度,而容器的底长变短了,则容器的容积一定会变小,即移动aj并不能帮助我们找到更大的容积。也就是说,每次向中间靠拢的时候,移动的边应该是当前容器两条边中较短的那条边。将每一次靠拢后的容积与先前求得的最大值进行比较,如果更大,则取代原最大值。注意,这种算法对每条边只会遍历一次,时间复杂度是 O ( n )

代码

class Solution:
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        max_area = 0
        left = 0
        right = len(height) - 1
        while left < right:
            if height[left] < height[right]:
                tmp_area = height[left] * (right - left)
                left += 1
            else:
                tmp_area = height[right] * (right - left)
                right -= 1
            max_area = max(max_area, tmp_area)
        return max_area

猜你喜欢

转载自blog.csdn.net/Draymond_666/article/details/80055015