这个解题思路来自代码随想录:代码随想录 (programmercarl.com)
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
std::unordered_map <int,int> map;
for(int i = 0; i < nums.size(); i++) {
// 遍历当前元素,并在map中寻找是否有匹配的key
auto iter = map.find(target - nums[i]);
if(iter != map.end()) {
return {iter->second, i};
}
// 如果没找到匹配对,就把访问过的元素和下标加入到map中
map.insert(pair<int, int>(nums[i], i));
}
return {};
}
};
小编自己写的方法实测不佳,但可作为一个解题思路
// 方法一:效果差
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> v;
int count = 0;
unordered_map<int,pair<int,int>> mp;
int tmp;
for(int i=0;i<nums.size();i++) {
count = 0;
if(mp.count(target-nums[i])!=0) {
count++;
mp[target-nums[i]].second = count;
}
tmp = target-nums[i];
mp.insert({nums[i],{tmp,count}});
v.push_back(i);
}
for(int i=0;i<v.size();i++) {
// cout<<"v[i]"<<v[i]<<endl;
// cout<<"mp[nums[v[i]]].second"<<mp[nums[v[i]]].second<<endl;
if(mp[nums[v[i]]].second==0) {
v.erase(v.begin() + i);
i--;
}
}
return v;
}
};
// 方法二:效果不佳
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> v;
int count = 0;
unordered_map<int,pair<int,int>> mp;
int tmp;
int k=0;
int tmp_index;
for(int i=0;i<nums.size();i++) {
tmp = target-nums[i];
if(tmp==nums[i]) {
k++;
if(k==1)
tmp_index = i;
else if(k==2) {
// mp.insert({nums[i],{tmp_index,i}});
// k=0;
return {tmp_index,i};
}
}else {
if(mp.count(tmp)!=0) {
mp.insert({nums[i],{-1,i}});
}else{
mp.insert({nums[i],{i,-1}});
}
}
}
for(auto it:mp) {
if(it.second.second !=-1) {
tmp = target-it.first;
// cout<<it.first<<":"<<it.second.first<<","<<it.second.second<<endl;
// cout<<mp.find(tmp)->first<<":"<<mp.find(tmp)->second.first<<","<<mp.find(tmp)->second.second<<endl;
v.push_back(it.second.second);
v.push_back(mp.find(tmp)->second.first);
}
}
return v;
}
};