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 node{
int data;
int pos;
node(int idata, int ipos){
data = idata;
pos = ipos;
}
};
bool raise(node a, node b){ return (a.data < b.data);}
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector <node> temp;
vector <int> res;
int i = 1;
for(auto it = numbers.begin(); it < numbers.end(); it++, i++)
{
node n(*it,i);
temp.push_back(n);
}
sort(temp.begin(), temp.end(),raise);
auto pBegin = temp.begin();
auto pEnd = temp.end() -1;
while(pBegin <pEnd) {
if((*pBegin).data + (*pEnd).data == target){
res.push_back((*pBegin).pos > (*pEnd).pos ? (*pEnd).pos : (*pBegin).pos);
res.push_back((*pBegin).pos < (*pEnd).pos ? (*pEnd).pos : (*pBegin).pos);
return res;
} else if((*pBegin).data + (*pEnd).data > target){
pEnd--;
} else {
pBegin++;
}
}
return res;
}
};
注意:
1.返回的是索引,而不是数值.
2.迭代器auto it = numbers.end(); 此时it指向最后一个元素的末尾,不能直接 *it.