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

DAY6:leetcode #11 Container With Most Water

2016-04-26 10:12 531 查看
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.

一开始用了两层循环遍历的思路,超时。看到了这样的思路:采用两个指针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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: