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

Container With Most Water——双指针

2015-06-09 17:25 429 查看
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.

用两个指针从数组的左边和右边开始,向中间搜索。依据的理由有两点:
1、因为一开始底边长就已经是最大,两个指针向中间移动的时候,底边长只会变短,因此如果此时面积要变大的话,只能是两条高中的最短者比移动前的最短高更高,
2、因此,每次选择移动左指针还是右指针,优先选择当前高度最短的那个,以期寻找到更高的边。如果此时选择移动当前高度最高的那个,就有可能跳过了最优解。

直观的解释是:容积即面积,它受长和高的影响,当长度减小时候,高必须增长才有可能提升面积,所以我们从长度最长时开始递减,然后寻找更高的线来更新候补;

没怎么用过Python写过程序,所以决定用Python来写写,结果错误百出。

出错的地方如下:

1,python在for循环,while,if等语句中不用括号,应该用缩进和:

2,和c++一样python需要特比的注意中文输入,这个程序就是有个中文的:,害得我一直不知道错在哪.

class Solution:
# @param {integer[]} height
# @return {integer}
def maxArea(self, height):
Maxlenth=len(height)
if 1 == Maxlenth:
return 0
StartPos=0
MaxLeft=height[StartPos]
EndPos=Maxlenth-1
MaxRight=height[EndPos]
MaxCont=0
while StartPos<EndPos:
if  height[StartPos]>=height[EndPos]:
T=height[EndPos]*(EndPos-StartPos)
EndPos-=1
if height[EndPos]>MaxRight:
MaxRight=EndPos
else:
T=height[StartPos]*(EndPos-StartPos)
StartPos+=1
if height[StartPos]>MaxLeft:
MaxLeft=StartPos
if T>MaxCont:
MaxCont=T
return MaxCont
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: