暴力法:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int i,j;
for(i=0;i<nums.size()-1;i++)
{
for(j=i+1;j<nums.size();j++)
{
if(nums[i]+nums[j]==target)
{
return {i,j};
}
}
}
return {i,j};
};
};
哈希表:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> ans;
unordered_map<int,int>hashmap;
for(int i=0;i<nums.size();i++){
if(hashmap[target-nums[i]]&&hashmap[target-nums[i]]!=i+1)
{
//防止利用同个元素
ans.push_back(i);
ans.push_back(hashmap[target-nums[i]]-1);
return ans;
}
hashmap[nums[i]]=i+1;
//将hash表对应下标+1,防止处理下标为0的情况
}
return ans;
}
};