Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
class Solution
{
public:
vector<int> twoSum(vector<int> &numbers, int target)
{
vector<int> num = numbers;
std::sort(num.begin(), num.end());
int length = numbers.size();
int left = 0;
int right = length - 1;
int sum = 0;
vector<int> index;
while(left < right)
{
sum = num[left] + num[right];
if(sum == target)
{
// find the index from the old array
for(int i = 0; i < length; ++i)
{
if(numbers[i] == num[left])
{
index.push_back(i);
}
else if(numbers[i] == num[right])
{
index.push_back(i);
}
if(index.size() == 2)
{
break;
}
}
break;
}
else if(sum > target)
{
--right;
}
else
{
++left;
}
}
return index;
}
};