标签:
用两个指针从数组的左边和右边开始,向中间搜索。依据的理由有两点:
1、因为一开始底边长就已经是最大,两个指针向中间移动的时候,底边长只会变短,因此如果此时面积要变大的话,只能是两条高中的最短者比移动前的最短高更高,否则就无需考察,直接continue到下一次的循环。
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
标签:
原文地址:http://www.cnblogs.com/qiaozhoulin/p/4564098.html