//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
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;
struct node
{
int data;
int index;
node()
{
}
node(const node &t)
{
data = t.data;
index = t.index;
}
node(int da, int ind)
{
data = da;
index = ind;
}
};
bool cmp(const node &a, const node &b)
{
return a.data < b.data;
}
class Solution {
public:
/***超时****/
vector<int> twoSum(vector<int> &numbers, int target)
{
vector <int> v;
int ind1 = 0;
int ind2 = 0;
for(int i = 0; i<numbers.size(); i++)
{
ind1 = i;
bool isExist = false;
for(int j = i ; j< numbers.size(); j++)
{
if(numbers[j] == target - numbers[i])
{
ind2 = j;
isExist = true;
break;
}
}
if(isExist)break;
}
v.push_back(ind1 + 1);
v.push_back(ind2 + 1);
return v;
}
vector<int> twoSum_sort(vector<int> &numbers, int target)
{
vector <int> v;
int ind1 = 0;
int ind2 = numbers.size() - 1;
/***将原vector保存其值和对应索引到一个vector中***/
vector<node>vn;
for (int i = 0 ; i< numbers.size(); i++)
{
node t;
t.data = numbers[i];
t.index = i+1;
vn.push_back(t);
}
sort(vn.begin(), vn.end(), cmp);
/***排序后,两个指针:一前一后,向中间找***/
while (ind1 < ind2)
{
if (vn[ind2].data + vn[ind1].data > target)
{
ind2--;
}
else if(vn[ind2].data + vn[ind1].data < target)
{
ind1++;
}
else
break;
}
v.push_back(((vn[ind1].index)<vn[ind2].index)?(vn[ind1].index):(vn[ind2].index));
v.push_back(((vn[ind1].index)>vn[ind2].index)?(vn[ind1].index):(vn[ind2].index));
return v;
}
vector<int> twoSum_hash(vector<int> &numbers, int target)
{
vector <int> v;
/***创建一个hash,把numbers每个元素和对应索引存储进去***/
map<int, int>mp;
for (int i = 0 ; i<numbers.size(); i++)
{
mp[numbers[i]]=i;
}
int j = 0;
map<int, int>::iterator k = mp.begin();
/***对于numbers中的每个元素s,查找(target - s)是否在hash中***/
while (j<mp.size())
{
k =mp.find(target - numbers[j]);
if ((k != mp.end()) && j!= k->second)//不能是他自身
{
v.push_back(j+1);
v.push_back(k->second + 1);
break;
}
j++;
}
return v;
}
};
int main()
{
/*vector<int> v;
v.push_back(0);
v.push_back(3);
v.push_back(4);
v.push_back(15);
v.push_back(8);
v.push_back(10);
v.push_back(14);
v.push_back(16);
v.push_back(20);*/
vector<int> v;
v.push_back(5);
v.push_back(75);
v.push_back(25);
Solution s;
//cout<<(s.twoSum(v,12))[0]<<endl;
//cout<<(s.twoSum(v,12))[1]<<endl;
//s.twoSum1(v,8);
//cout<<s.twoSum_sort(v,12)[0]<<endl;
//cout<<s.twoSum_sort(v,12)[1]<<endl;
cout<<s.twoSum_sort(v,100)[0]<<endl;
cout<<s.twoSum_sort(v,100)[1]<<endl;
return 0;
}
TwoSum
最新推荐文章于 2018-07-31 23:03:28 发布