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
//Again!!!!
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
struct Entity
{
int index;
int value;
};
/*
注意:compare函数前一定要加static,不然编译时会出错
具体解释,参见网址:http://www.w2bc.com/Article/19411
sort中的比较函数compare要声明为静态成员函数或全局函数,不能作为普通成员函数,否则会报错。
因为:非静态成员函数是依赖于具体对象的,而std::sort这类函数是全局的,因此无法再sort中调用非静态成员函数。
静态成员函数或者全局函数是不依赖于具体对象的, 可以独立访问,无须创建任何对象实例就可以访问。同时静态成员函数不可以调用类的非静态成员。
*/
static bool compare(Entity& a, Entity& b)
{
return a.value < b.value;
}
class Solution {
public:
/* time:18ms
*/
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> result;
Entity *all = new Entity[numbers.size()];
for (int i = 0; i < numbers.size(); i++)
{
all[i].index = i;
all[i].value = numbers[i];
}
sort(all, all+numbers.size(),compare); //先将数组按升序排序,
int start = 0, end = numbers.size() - 1;
while (start < end) //在利用一前一尾的指针,来前后移动找到我们要找的两个结果值
{
if ((all[start].value + all[end].value) == target)
{
if (all[start].index>all[end].index)
{
int temp;
temp = all[start].index;
all[start].index = all[end].index;
all[end].index = temp;
}
result.push_back(all[start].index+1);
result.push_back(all[end].index+1);
break;
}
else if ((all[start].value + all[end].value) > target)
{
end--;
}
else
{
start++;
}
}
return result;
}
};
//第二种方法:利用C++中的hash_map(map)(hash_map的查询速度比map的高,具体的差别请大家上网查查就知道啦,)
vector<int> twoSum_e2(vector<int> &numbers, int target) {
hash_map<int, int> hm; // numbers值,numbers值的下标
vector<int> result; // 保存结果
int size = numbers.size();
if (size == 0)
return result;
for (int i = 0; i < numbers.size(); ++i)
{
hm[numbers[i]] = i+1;
}
for (int i = 0; i < size; ++i)
{
hash_map<int, int>::iterator iter = hm.find(target - numbers[i]);
if (iter != hm.end() && (i+1)!=iter->second) //如果找到另一个值,且与当前值不重复
{
int k = i + 1;
if (k >(iter->second))
{
int temp = k;
k = iter->second;
iter->second = temp;
}
result.push_back(k);
result.push_back(iter->second);
break;
}
}
return result;
}
void main()
{
vector<int> numbers = { 7, 2, 11, 15 };
Solution s;
int target = 9;
vector<int> result(2);
result = s.twoSum(numbers, target);
for (int i = 0; i < result.size(); i++)
cout << result[i] <<"--";
cout << endl;
}