forked from daiwb/Algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwoSum.cpp
More file actions
25 lines (24 loc) · 740 Bytes
/
TwoSum.cpp
File metadata and controls
25 lines (24 loc) · 740 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int n = numbers.size();
vector<pair<int, int> > mm;
for (int i = 0; i < n; ++i) mm.push_back(make_pair(numbers[i], i + 1));
sort(mm.begin(), mm.end());
int lp = 0, rp = n - 1;
while (lp < rp) {
int sum = mm[lp].first + mm[rp].first;
if (sum == target) break;
else if (sum < target) ++lp;
else --rp;
}
vector<int> ret;
ret.push_back(min(mm[lp].second, mm[rp].second));
ret.push_back(max(mm[lp].second, mm[rp].second));
return ret;
}
};