-
Notifications
You must be signed in to change notification settings - Fork 0
/
two_sum.cc
70 lines (59 loc) · 1.39 KB
/
two_sum.cc
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Copyright 2014 kevinew@leetcode Inc. All Rights Reserved.
#include <algorithm>
#include <cmath>
#include <string>
#include <vector>
#include <iostream>
using namespace std;
struct Data {
int number, id;
};
bool Cmp(const Data& a, const Data& b) {
return a.number < b.number;
}
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> result;
vector<Data> datas;
for (int i = 0; i < numbers.size(); ++i) {
Data d;
d.number = numbers[i];
d.id = i + 1;
datas.push_back(d);
}
sort(datas.begin(), datas.end(), Cmp);
int i, j;
i = 0;
j = datas.size() -1;
while (i < j) {
if (datas[i].number + datas[j].number == target) {
if (datas[i].id < datas[j].id) {
result.push_back(datas[i].id);
result.push_back(datas[j].id);
} else {
result.push_back(datas[j].id);
result.push_back(datas[i].id);
}
return result;
} else if (datas[i].number + datas[j].number < target) {
++i;
} else {
--j;
}
}
}
};
int main(int argc, char **argv) {
Solution s;
vector<int> n;
n.push_back(2);
n.push_back(7);
n.push_back(8);
n.push_back(9);
n = s.twoSum(n, 9);
for (int i = 0; i < n.size(); ++i) {
cout << n[i] << endl;
}
return 0;
}