您的位置:首页 > 大数据 > 人工智能

Container With Most Water - LeetCode

2015-04-07 20:24 288 查看

Container With Most Water - LeetCode

题目:



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.

分析:

这道题目一开始没注意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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: