两数之和
暴力解法
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int n=nums.size();
for(int i=0; i<n;i++)
{
for(int j=i+1; j<n; j++)
{
int sum=nums[i]+nums[j];
if(sum==target)
return{i,j};
}
}
return {};
}
};
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int n=nums.size();
for(int i=0; i<n;i++)
{
int a=target-nums[i];
for(int j=i+1; j<n;j++)//如果从0开始过不了[3,2,4]和6。因为双3也可以通过。
{
if(nums[j]==a)
return{i,j};
}
}
return {};
}
};
hashmap
https://blog.csdn.net/woshimaxiao1/article/details/83661464
https://www.jianshu.com/p/e136ec79235c
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int n=nums.size();
unordered_map<int,int> hashtable;
for(int i=0; i<n;i++)
{
auto it=hashtable.find(target-nums[i]);
if(it!=hashtable.end())//如果没有查完表没有查到
{
return{it->second,i};
}
hashtable[nums[i]]=i;//根据值插入索引
}
return {};
}
};