您的位置:首页 > 其它

leetcode 1 Two Sum

2015-03-18 15:24 375 查看
Two
Sum

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9

Output: index1=1, index2=2
思路:先排序;再从两头向中间找 O(nlogn)

class Solution:
# @return a tuple, (index1, index2)
def twoSum(self, num, target):
nums=zip(num[:],range(len(num)))
s=sorted(nums,key=lambda nums:nums[0])
#print s
i=0
j=len(s)-1
while i<j:
tmp=s[i][0]+s[j][0]
if tmp==target:
i,j=s[i][1]+1,s[j][1]+1
if i>j:
i,j=j,i
return (i,j)
elif tmp>target:
j-=1
else:
i+=1

更快更好的方法:用字典记录之前的所有数字,当在位置i时,O(1)的时间即可知道target-num[i]是否存在。 O(n)

class Solution:
# @return a tuple, (index1, index2)
def twoSum(self, num, target):
d={}
for i in xrange(len(num)):
if target-num[i] in d:
return(d[target-num[i]]+1,i+1)
d[num[i]]=i
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: