Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
方法1:最容易想到的方法就是枚举法了。很显然这样做会超时!
#include<iostream>
#include<vector>
#include<cstdio>
using namespace std;
vector<int> twoSum(vector<int> &numbers, int target)
{
int i,j;
vector<int> res;
for(i=0;i<numbers.size()-1;i++)
for(j=i+1;j<numbers.size();j++)
if(numbers[i]+numbers[j]==target)
{
res.push_back(i+1);
res.push_back(j+1);
}
return res;
}
int main(int argc,char *argv[])
{
freopen("input.txt","r",stdin);
vector<int> v,res;
int i,n,num,target;
cin>>n;
for(i=0;i<n;i++)
{
cin>>num;
v.push_back(num);
}
cin>>target;
res=twoSum(v,target);
cout<<res[0]<<" "<<res[1]<<endl;
return 0;
}
方法2:先用map将值映射到下标,然后再对数组排序,对排序后的数组进行查找两个数使之和为target。但这样做会有个问题对有重复元素时失效:
Input:[0,4,3,0], 0
Output:4,4
Expected:1, 4
vector<int> twoSum(vector<int> &numbers, int target) {
int i,j;
vector<int> res;
map<int,int> mymap;
int len=numbers.size();
for(i=0;i<len;i++)
mymap[numbers[i]]=i+1;
sort(numbers.begin(),numbers.end());
i=0,j=numbers.size()-1;
while(i<j)
{
int sum=numbers[i]+numbers[j];
if(sum==target)
{
res.push_back(mymap[numbers[i]]);
res.push_back(mymap[numbers[j]]);
break;
}else if(sum>target)
j--;
else
i++;
}
return res;
}
方法3:采用map自带的查找的方法。
class Solution {
public:
vector<int> twoSum(vector<int> &numbers,int target)
{
map<int,int> mymap;
for(int i=0;i<numbers.size();i++)
mymap[numbers[i]]=i+1;
vector<int> res;
for(int i=0;i<numbers.size();i++)
{
int a=numbers[i];
int b=target-a;
map<int,int>::iterator map_it=mymap.begin();
map_it=mymap.find(b);
if(map_it!=mymap.end())
{
int index1=i+1;
int index2=map_it->second;
if(index1==index2)//这里很关键,保证不会将某个数取两次
continue;
res.push_back(index1);
res.push_back(index2);
break;
}
}
return res;
}
};