1.枚举法
暴力搜索匹配
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int>result;
for(int i=0;i<nums.size();i++)
{
for(int j=i+1;j<nums.size();j++)
{
if(nums[i]+nums[j]==target)
{
result.push_back(i);
result.push_back(j);
}
}
}
return result;
}
};
2.哈希表
class Solution
{
public:
vector<int> twoSum(vector<int>&nums,int target)
{
vector<int>result;
unordered_map<int,int>haxibiao;
for(int i=0;i<nums.size();i++)
{
unordered_map<int,int>::iterator it;
it = haxibiao.find(target-nums[i]);
if(it!= haxibiao.end())
{
result.push_back(it->second);
result.push_back(i);
}
haxibiao[nums[i]]=i;
}
return result;
}
};