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

leetcode(11) Container With Most Water

2017-07-22 12:09 344 查看

problem

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
4000
.

暴力解法

直接用乘法计算后比较

class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""

ans = 0
n = len(height)

for i in range(n):
for j in range(i+1, n):
if (j - i)*min(height[i], height[j])>ans:
ans = (j - i)*min(height[i], height[j])
#ans = max(ans, (j - i)*min(height[i], height[j]))

return ans


用加法比较

class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""

ans = 0
n = len(height)
tmp = [0 for _ in range(n)]
for i in range(n):
step = 0
for j in range(n):
if height[j]>=height[i] and abs(j-i)>step:
step = abs(j-i)
tmp[i] = height[i] *step

return max(tmp)


这两种算法时间复杂度都是O(n2)

two point approach

设两个指针i,j分别指向列表的两端,计算height[i]和height[j]构成的长方形的面积,将短的指针向中间移动,假设height[i]>height[j],设f(i, j)表示i和j之间可以形成的最大的面积,
area(i, j)=abs(j-i)*height[j]
,那么
f(i, j) = max(area(i, j), f(i, j-1))
,这是建立在
area(i, j) >= area(k, j) for i<=k<=j
(因为这些长方形高度最高不会超过
height[j]
) ,放到排列组合中就是C2n=C2n−1+n−1,但是我们利用上述性质(
area(i, j) >= area(k, j) for i<=k<=j
),使得C2n=C2n−1+n−1变成了C2n=C2n−1+1 因此O(n2)变成了O(n)。

实际就是一种贪心算法。

class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""

i = 0
j = len(height)-1
tmp=[]

while i!=j:
tmp.append((j-i)*min(height[i], height[j]))
if height[i] < height[j]:
i += 1
else:
j -= 1

return max(tmp)


这个是在leetcode上看到的比较快速的算法:

class Solution(object):
def maxArea(self, height):
i=0
j=len(height)-1
max_s=0
while i!=j:
# 比上面的代码少比较一次,省去了min()
if height[i]>height[j]:
s=height[j]*(j-i)
j-=1
if s>max_s:
max_s=s
else:
s=height[i]*(j-i)
i+=1
if s>max_s:
max_s=s
return max_s
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode