leetcode之3Sum Closest
2016-01-05 17:27
561 查看
这题基本框架利用了3Sum,当然了没那么多的内容,稍微简化下就好了。代码如下:
如果当nums个数少,但是sum又偏离很多的时候,直接求出nums所有的解再来比较应该反而能快一点吧。。比较头3个数字以及后3个数字的和来缩小范围应该可以减少很多时间。我就不写了,比较简单。
class Solution(object): def threeSumClosest(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ def threeSum(nums, sum1): nums=sorted(nums) n=len(nums) if n==0: return 0 if n <= 3: if sum(nums) == sum1: return True else: return None i=0 while i<n: l,r=i+1,n-1 target=sum1 -nums[i] while l<r: if nums[l]+nums[r]==target: return sum1 elif nums[l]+nums[r] < target: l+=1 else: r-=1 i = i + 1 else: return None for i in range(10000): if threeSum(nums, target + i) != None: return target + i if threeSum(nums, target - i) != None: return target - i
如果当nums个数少,但是sum又偏离很多的时候,直接求出nums所有的解再来比较应该反而能快一点吧。。比较头3个数字以及后3个数字的和来缩小范围应该可以减少很多时间。我就不写了,比较简单。
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法