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
注:时间复杂度为O(N*N)的通过不了,所以采用排序,然后首尾逼近,时间复杂度就是排序的O(N*logN),因为排序后数据标号变了,所以定义了一个结构体保存数据及其下标。
struct iNode {
int num;
int index;
};
bool cmp(const iNode &a, const iNode &b)
{
return a.num < b.num;
}
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> result;
vector<iNode> ivec;
for (int i = 0; i < numbers.size(); i++) {
iNode node;
node.num = numbers[i];
node.index = i;
ivec.push_back(node);
}
sort(ivec.begin(), ivec.end(), cmp);
int i = 0, j = ivec.size() - 1, sum = 0;
while (i != j) {
sum = ivec[i].num + ivec[j].num;
if (sum == target) {
if (ivec[i].index < ivec[j].index) {
result.push_back(ivec[i].index + 1);
result.push_back(ivec[j].index + 1);
}
else {
result.push_back(ivec[j].index + 1);
result.push_back(ivec[i].index + 1);
}
break;
}
else if (sum > target)
j--;
else
i++;
}
return result;
}
};