双指针 and 排序:
bool lessthan(const pair<int,int>& lhs,const pair<int,int>& rhs){
if(lhs.first == rhs.first)
return lhs.second < rhs.second;
return lhs.first < rhs.first;
}
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
vector<pair<int,int>> vnum;
for (size_t i = 0; i < numbers.size() ; ++i){
vnum.push_back(make_pair(numbers[i],i));
}
sort(vnum.begin(),vnum.end(),lessthan);
vector <int> result;
int s = 0;
int e = vnum.size()-1;
while(s < e){
if(vnum[s].first + vnum[e].first == target){
result.push_back(min(vnum[s].second,vnum[e].second));
result.push_back(max(vnum[s].second,vnum[e].second));
break;
}
else if (vnum[s].first + vnum[e].first > target)
e -= 1;
else
s += 1;
}
return result;
}
};