-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwoSum
More file actions
57 lines (53 loc) · 1.37 KB
/
Copy pathTwoSum
File metadata and controls
57 lines (53 loc) · 1.37 KB
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
/*======================================================================================================================
输入一个integer型数组和一个integer型整数target,输出数组中两个数相加结果等于target
=======================================================================================================================*/
#include<iostream>
#include<vector>
#include<iterator>
#include<map>
#include<algorithm>
using namespace std;
typedef pair<vector<int>::iterator, vector<int>::iterator> iterator_pair;
iterator_pair TwoSum(vector<int> &coll, const int sum)
{
vector<int>::iterator first = coll.begin();
vector<int>::iterator last = --coll.end();
int temp;
while (first != last)
{
temp = *first + *last;
if (temp > sum)
last--;
else if (temp < sum)
first++;
else
break;
}
temp = *first + *last;
iterator_pair p(coll.end(), coll.end());
if (temp == sum)
{
p.first = first;
p.second = last;
}
return p;
}
int main()
{
vector<int> array;
array.push_back(7);
array.push_back(3);
array.push_back(8);
array.push_back(9);
array.push_back(12);
array.push_back(20);
array.push_back(76);
sort(array.begin(), array.end());
copy(array.begin(), array.end(), ostream_iterator<int>(cout, " "));
iterator_pair p;
p = TwoSum(array, 16);
cout << endl;
cout << *p.first << " " << *p.second << endl;
system("pause");
return 0;
}