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 {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> r;
for(int i = 0; i < nums.size(); i++) {
for(int j = i + 1; j < nums.size(); j++) {
if( (nums[i] + nums[j]) == target ) {
r.push_back(++i);
r.push_back(++j);
return r;
}
}
}
return r;
}
};
上述算法的复杂度为 n 的平方,超时。
优化思路有两个,一个是复制一份,进行排序,查找到该元素的值后,去原数组中寻找下标,然后返回。
另一种,就是利用哈希表,将值和下标对应起来,一次遍历即可。
我实现的是哈希表的方式:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> r(2);
unordered_map<int, int> m;
for(int i = 0; i < nums.size(); i++) {
if(m.find(target - nums[i]) != m.end()) {
r[0] = m[target - nums[i]] + 1;
r[1] = i + 1;
} else {
m.insert(make_pair(nums[i], i));
}
}
return r;
}
};