leetcode-1-两数之和
bool cmp(pair<int, int> a, pair<int, int> b) {
return (a.first < b.first);
}
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<pair<int, int>> indexvec; //值,索引
vector<int> res;
int N=nums.size(), left =0, right = N-1, i=0;
for (auto it = nums.begin(); it != nums.end(); it++) {
indexvec.push_back(make_pair(*it, i++));
}
sort(indexvec.begin(), indexvec.end(), cmp);
while (left < right) {
while (indexvec[left].first + indexvec[right].first < target && left<right) {
left++;
}
while (indexvec[left].first + indexvec[right].first > target && left < right) {
right--;
}
if (indexvec[left].first + indexvec[right].first == target) {
res.push_back(indexvec[left].second);
res.push_back(indexvec[right].second);
break;
}
}
return res;
}
};
int main()
{
Solution sol;
vector<int> input = { 2, 7, 9, 11, 5, 8 }, res;
int target = 20;
res = sol.twoSum(input, target);
for (auto it = res.begin(); it != res.end(); it++) {
cout << *it << ",";
}
cout<< endl;
return 0;
}