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 + n),也就是O(nlogn)。
代码(注意,这里的代码只是返回了数字本身,而不是题目中要求的下标,要知道下标的话还需要建立数字和原来的下标之间的映射):
class Solution {
public:
vector<int> twoSum(vector<int> &num, int target) {
if(num.size() < 2)
return {};
sort(num.begin(), num.end());
vector<int> temp(2);
int p1(0), p2(num.size()-1);
while(p1 < p2) {
int sum = num[p1]+num[p2];
if(sum == target) {
temp[0] = num[p1];
temp[1] = num[p2];
break;
}
else if(sum < target)
++p1;
else
--p2;
}
return temp;
}
};
第二种,使用hash表,对每个数字num[i],查找target-num[i]是否存在,复杂度为O(n)。
代码:
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
unordered_map<int, int> hash;
for(int i = 0; i != numbers.size(); ++i) {
hash[numbers[i]] = i+1;
}
vector<int> result(2);
for(int i = 0; i != numbers.size(); ++i) {
int value = target-numbers[i];
if(hash.find(value) != hash.end() && hash[value] != i+1){
result[0] = i+1;
result[1] = hash[value];
break;
}
}
return result;
}
};