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需要特比的注意中文输入,这个程序就是有个中文的:,害得我一直不知道错在哪.
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
相关文章推荐
- LeetCode之“动态规划”:Climbing Stairs
- org.tinygroup.beancontainer-IOC、AOP框架
- POJ1995 Raising Modulo Numbers 快速幂取模
- 使用Genymotion调试出现错误INSTALL_FAILED_CPU_ABI_INCOMPATI
- HCE AID选择策略测试
- http://blog.csdn.net/lenotang/article/details/2823230
- leetcode_Factorial Trailing Zeroes_easy
- Leetcode[219]-Contains Duplicate II
- 水题 Codeforces Beta Round #70 (Div. 2) A. Haiku
- sleep() 和 wait() 有什么区别?
- MacBook Air 使用技巧
- Genymotion首次运行程序出现错误Installation error: INSTALL_FAILED_CPU_ABI_INCOMPATIBLE
- sctp AIX
- Contains Duplicate III 重复数 堆实现
- Contains Duplicate II 重复数HASH
- Mesos单点Master集群部署和High Availability集群部署
- [Selenium]重写拖拽dragWidgetToElementContainner()
- 在main()之前,IAR都做了啥?
- mail.rc配置外网发邮件
- POJ 1422 Air Raid (二分图最小点集覆盖 匈牙利算法)