题目:
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
C++解答一(传统方法,Runtime: 19 ms):
struct Node
{
int num;
int pos;
}; bool cmp(Node a,Node b)
{
return a.num<b.num;
} class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) { vector<int> result;
vector<Node> tmp;
Node a; for(int i = ;i<numbers.size();i++)
{
a.pos = i+;
a.num = numbers[i];
tmp.push_back(a);
} sort(tmp.begin(),tmp.end(),cmp);
int j = tmp.size()-;
int tmpvalue = ; for(int i = ;i<tmp.size();)
{
tmpvalue = tmp[i].num+tmp[j].num;
if(tmpvalue==target)
{
if(tmp[i].pos<tmp[j].pos)
{
result.push_back(tmp[i].pos);
result.push_back(tmp[j].pos);
}
else
{
result.push_back(tmp[j].pos);
result.push_back(tmp[i].pos);
} break;
}
else if(tmpvalue>target)
{
j--;
}
else
{
i++;
}
} return result;
}
};
C++ 解答二(巧妙方法,Runtime: 35 ms):
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
int i, sum;
vector<int> results;
map<int, int> hmap;
for(i=; i<numbers.size(); i++){
if(!hmap.count(numbers[i])){
hmap.insert(pair<int, int>(numbers[i], i));
}
if(hmap.count(target-numbers[i])){
int n=hmap[target-numbers[i]];
if(n<i){
results.push_back(n+);
results.push_back(i+);
return results;
} }
}
return results;
}
};