题目描述
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
思路描述
在数字序列中寻找两数之和等于目标数,首先想到的就是先对序列排队,然后从两边逼近目标数。如果和偏大,减小和,也就是后面的索引向前移动,反之,前面的索引向后移动,从而最终找到答案。
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> oput;
vector<int> vec;
for (int m = 0; m < numbers.size(); m++)
{
vec.push_back(numbers[m]);
}
sort(numbers.begin(), numbers.end());
int i = 0;
int j = numbers.size() - 1;
int sum;
do
{
sum = numbers[i] + numbers[j];
if (target == sum)
break;
else if (target > sum)
i++;
else
j--;
} while (true);
for (int m = 0;m < vec.size(); m++)
{
if (vec[m] == numbers[i] || vec[m] == numbers[j])
oput.push_back(m + 1);
if (oput.size() == 2)
break;
}
return oput;
}
};