标签:
1. 题目 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
给定一个整数数组,找出其中两个数满足相加等于你指定的目标数字。
要求:这个函数twoSum必须要返回能够相加等于目标数字的两个数的索引,且index1必须要小于index2。请注意一点,你返回的结果(包括index1和index2)都不是基于0开始的。
你可以假设每一个输入肯定只有一个结果。
2. c++解题
2.1 两层循环,时间复杂度为o(n^2),空间复杂度为o(1)
class Solution { public: vector<int> twoSum(vector<int> &numbers, int target) { vector<int> result; for (int i = 0; i < numbers.size()-1; i++) { for (int j = i+1; j < numbers.size(); j++) { if (numbers[i] + numbers[j]==target) { result.push_back(i+1); result.push_back(j+1); return result; } } } return result; } };
2.2 哈希,时间复杂度为o(n),空间复杂度为o(n)
class Solution { public: vector<int> twoSum(vector<int> &numbers, int target) { vector<int> result; map<int, int> m; if (numbers.size() < 2) return result; for (int i = 0; i < numbers.size(); i++) m[numbers[i]] = i; map<int, int>::iterator it; for (int i = 0; i < numbers.size(); i++) { if ((it = m.find(target - numbers[i])) != m.end()) { if (i == it->second) continue; result.push_back(i+1); result.push_back(it->second+1); return result; } } return result; } };
3. python 解题
将原来的数组深拷贝一份,然后排序---然后在排序后的数组中找两个数使它们相加为target:使用两个指针,一个指向头,一个指向尾,两个指针向中间移动并检查两个指针指向的数的和是否为target。如果找到了这两个数,再将这两个数在原数组中的位置找出来就可以了---要注意的一点是:在原来数组中找下标时,需要一个从头找,一个从尾找,要不无法通过。如这个例子:numbers=[0,1,2,0]; target=0。如果都从头开始找,就会有问题。
3.1
class Solution:
# @return a tuple, (index1, index2)
def twoSum(self, num, target):
index = []
numtosort = num[:] //深拷贝
numtosort.sort()
i = 0; j = len(numtosort) - 1
while i < j:
if numtosort[i] + numtosort[j] == target:
for k in range(0,len(num)):
if num[k] == numtosort[i]:
index.append(k)
break
for k in range(len(num)-1,-1,-1):
if num[k] == numtosort[j]:
index.append(k)
break
index.sort()
break
elif numtosort[i] + numtosort[j] < target:
i = i + 1
elif numtosort[i] + numtosort[j] > target:
j = j - 1
return (index[0]+1,index[1]+1)
3.2 字典
class Solution:
# @return a tuple, (index1, index2)
def twoSum(self, num, target):
dict = {}
for i in range(len(num)):
x = num[i]
if target-x in dict:
return (dict[target-x]+1, i+1) //找到,返回两数的下标
dict[x] = i
标签:
原文地址:http://www.cnblogs.com/zxqstrong/p/4561368.html