DAY6:leetcode #11 Container With Most Water

来源:互联网 发布:电脑txt小说编辑软件 编辑:程序博客网 时间:2024/04/30 12:03

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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.

一开始用了两层循环遍历的思路,超时。看到了这样的思路:采用两个指针l和r,初始化分别指向数组的两端,然后在向中间移动找到最大容量。如果l指向的数字小,则l需要右移才有可能获得更大容量,因为此时如果左移r,得到的容量肯定比左移r之前的容量小(高度已经被较小的l限制住了)。如果r指向的数字小,则需要左移r。这样,当l和r相遇的时候,最大的容量就是我们需要的。

class Solution(object):    def maxArea(self, height):        """        :type height: List[int]        :rtype: int        """        max_v = 0        i = 0        j = len(height) - 1        while True:            if max_v < (j-i)*min(height[i],height[j]):                max_v = (j-i)*min(height[i],height[j])            if height[i] < height[j]:                i += 1            else:                j -= 1            if i == j:                break        return max_v                


0 0
原创粉丝点击