-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtwoSum.cc
105 lines (100 loc) · 3.09 KB
/
twoSum.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include <stdio.h>
#include <vector>
#include <algorithm>
#include <iostream>
#include <map>
class Solution
{
private:
void sort(std::vector< std::pair<int, int> > &ns_index, int left, int right)
{
if(left < right)
{
int mid = (right + left) / 2;
std::swap(ns_index[left], ns_index[mid]);
std::pair<int, int> key_pair = ns_index[left];
size_t i = left;
size_t j = right;
while ( i < j )
{
while( (i < j) && (ns_index[j].first >= key_pair.first))
--j;
if(i < j)
{
ns_index[i] = ns_index[j];
++i;
}
while((i < j) && (ns_index[i].first < key_pair.first))
++i;
if(i < j)
{
ns_index[j] = ns_index[i];
--j;
}
}
ns_index[i] = key_pair;
sort(ns_index, left, i - 1);
sort(ns_index, i + 1, right);
}
}
public:
std::vector<int> twoSum(std::vector<int>& numbers, int target)
{
std::vector<int> rets;
std::vector< std::pair<int, int> > ns_index;
for(int i = 0; i < numbers.size(); ++i)
ns_index.push_back(std::pair<int, int> (numbers[i], i));
sort(ns_index, 0, numbers.size() - 1);
int i = 0;
int j = numbers.size() - 1;
while(i < j)
{
int total = ns_index[i].first + ns_index[j].first;
if(total < target)
++i;
else if(total > target)
--j;
else
{
if(ns_index[i].second < ns_index[j].second)
{
rets.push_back(ns_index[i].second + 1);
rets.push_back(ns_index[j].second + 1);
}
else
{
rets.push_back(ns_index[j].second + 1);
rets.push_back(ns_index[i].second + 1);
}
return rets;
}
}
}
void test()
{
std::vector<int> ns;
ns.push_back(2);
ns.push_back(1);
ns.push_back(9);
ns.push_back(4);
ns.push_back(4);
ns.push_back(56);
ns.push_back(90);
ns.push_back(3);
for(size_t i = 0; i < ns.size(); i++)
{
std::cout<< ns[i] << std::endl;
}
std::vector<int> ret = twoSum(ns, 8);
for(size_t i = 0; i < ret.size(); i++)
{
std::cout<<"index="<<ret[i]<<" value="<<ns[ret[i]-1] << std::endl;
}
}
};
int main()
{
Solution t;
t.test();
std::cout<<std::endl;
}