Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, vector<int>> hash;
for(int i = 0; i < nums.size(); ++i)
hash[nums[i]].push_back(i);
vector<int> ans(2);
for(int i = 0; i < nums.size(); ++i){
auto it = hash.find(target - nums[i]);
if(it != hash.end() && (it->first != nums[i] || it->second.size() == 2)){
ans[0] = i;
ans[1] = it->second.back();
break;
}
}
return ans;
}
};
One pass. Handle the case where 2 * nums[i] == 2 * nums[j] == target, i != j
as a normal case.
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> hash;
vector<int> ans(2);
for(int i = 0; i < nums.size(); ++i){
auto it = hash.find(target - nums[i]);
if(it != hash.end()){
ans[0] = it->second;
ans[1] = i;
break;
}else{
hash[nums[i]] = i;
}
}
return ans;
}
};