暴力
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int i, j;
for (i = 0; i < nums.size(); ++i){
for(j = i + 1; j < nums.size(); ++j) {
if(nums[i] + nums[j] == target) {
return {i, j};
}
}
}
return {i, j};
}
};
两遍hash
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int, int> m;
vector<int> b(2, -1);
for(int i = 0; i < nums.size(); ++i){
m.insert(map<int, int>::value_type(nums[i], i));
}
for(int i = 0; i < nums.size(); ++i){
if(m.count(target - nums[i]) > 0 && m[target - nums[i]] != i){
b[0] = i;
b[1] = m[target - nums[i]];
break;
}
}
return b;
}
};
一遍hash
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int, int> m;
vector<int> b(2, -1);
for(int i = 0; i < nums.size(); ++i){
if(m.count(target - nums[i]) > 0){
b[0] = i;
b[1] = m[target - nums[i]];
break;
}
m[nums[i]] = i;
}
return b;
}
};