class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;
for(int i = 0 ; i < nums.size()-1 ; i++)
{
for(int j = i+1; j < nums.size() ; j++)
{
int sum = nums[i] + nums[j];
if(sum == target)
{
result.push_back(i);
result.push_back(j);
return result;
}
}
}
}
};
-
One-pass Hash Table
这里用了map,所以看一下是否有这个complement的值就行,不用回去一个一个地翻
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;
map<int,int> m;
for(int i = 0 ; i < nums.size() ; i++ )
{
int complement = target - nums[i];
if(m.find(complement)!=m.end())
{
result.push_back(i);
result.push_back(m[complement]);
return result;
}
else
m.insert(pair<int,int>(nums[i],i));
}
}
};
网友评论