own
#include <bits/stdc++.h>
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int i = 0, j = 0;
vector<int> result(2,0);
for(i = 0; i < nums.size(); i++){
int tmp;
tmp = target - nums[i];
int flag = 0;
for(j = i+1; j < nums.size(); j++){
if(tmp == nums[j]){
flag = 1;
break;
}
}
if(flag == 1){
break;
}
}
result[0] = i;
result[1] = j;
return result;
}
};
hash
#include <bits/stdc++.h>
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> hashtable;
for(int i = 0; i < nums.size(); i++){
auto it = hashtable.find(target - nums[i]);
if(it != hashtable.end()){
return {it->second, i};
}
hashtable[nums[i]] = i;
}
return {};
}
};
it->first代表键
it->secondi代表值
按照nums[i]设为键进行存储
存储的内容为i