Container With Most Water - LeetCode

Container With Most Water - LeetCode

题目:

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.


分析:

这道题目一开始没注意note,结果一直以为两线与x轴成一个梯形。。然后想了半天没想出来,其实是组成个矩形,就是一个盛水槽,这个我们知道,槽子的高度取决于两侧高度的短板,这样我们可以用两个指针,l在开头,r在结尾,当l<r时,我们希望提高l,所以l++;同理r<l时,我们希望提高r,所以r--。每一次循环都判断此时面积是否是大于res的,如果大于替换掉res。结束条件自然是当r=l时。

代码:

class Solution:
    # @return an integer
    def maxArea(self, height):
        if not height:
            return 0
        res = 0
        l = 0
        r = len(height)-1
        while l<r:
            res = max(res,min(height[l],height[r])*(r-l))
            if height[l]<height[r]:
                l += 1
            else:
                r -= 1
        return res


你可能感兴趣的:(LeetCode,python)