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
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
本文介绍了一种高效的方法来解决寻找数组中和为目标数的两个数的问题,包括排序法和哈希表法,详细解释了两种方法的实现步骤及复杂度。
828

被折叠的 条评论
为什么被折叠?



