题目:
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
struct number
{
int value;
vector<int>::size_type index;
number(){}
number(int v, vector<int>::size_type idx):value(v), index(idx){}
};
bool compare(const number &n1, const number &n2)
{
return n1.value < n2.value;
}
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<number> Number;
for(auto i = 0; i!=numbers.size(); ++i)
{
Number.push_back(number(numbers[i], i+1));
}
vector<int> result;
vector<int>::size_type index1=0, index2=0;
sort(Number.begin(), Number.end(), compare);
for(vector<int>::size_type iter1 = 0, iter2 = numbers.size()-1; iter1<iter2; )
{
if(Number[iter1].value+Number[iter2].value > target)
{
--iter2;
}
else if(Number[iter1].value+Number[iter2].value < target)
{
++iter1;
}
else
{
index1 = min(Number[iter1].index, Number[iter2].index);
index2 = max(Number[iter1].index, Number[iter2].index);
result.push_back(index1);
result.push_back(index2);
break;
}
}
return result;
}
};