标签:
给定一个数组和一个目标整数,已知这个目标整数一定等于给定数组中的某两个数字相加,求这两个数字在数组中的位置。
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
思路
对这个数组做拷贝,然后进行排序,设定两个指针head和tail,如果
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> num = numbers;
sort(num.begin(),num.end());
int head = 0, tail = num.size() - 1;
int tmpRes=0;
for (size_t i = 0; i < num.size(); i++)
{
tmpRes = num[head] + num[tail];
if ( tmpRes > target)
{
tail--;
continue;
}
if (tmpRes < target)
{
head++;
continue;
}
if (tmpRes == target)
{
break;
}
}
vector<int> resVec;
head = num[head];
tail = num[tail];
for (size_t i = 0; i < numbers.size(); i++)
{
if (numbers[i] == head || numbers[i] == tail)
{
resVec.push_back(i+1);
}
if (resVec.size() == 2)
break;
}
return resVec;
}
};
标签:
原文地址:http://www.cnblogs.com/flyjameschen/p/4376486.html