-
Notifications
You must be signed in to change notification settings - Fork 2
/
twoSum.cpp
40 lines (31 loc) · 893 Bytes
/
twoSum.cpp
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
/*
* This program solves the two sum problem: given S, find all the pairs of two
* integers in an unsorted array that sum up to S
*
* Naive O(N^2) solution
*
* @author J. Alvarez
*/
#include <iostream>
#include <set>
using namespace std;
void solve(set<pair<int, int>> & solution, int * array, int S, int N) {
for (int i = 0; i < N-1; i++)
for (int j = i+1; j < N; j++)
if (array[i] + array[j] == S)
solution.insert(pair<int, int>(array[i], array[j]));
}
void printSolution(const set<pair<int, int>> & solution) {
for(auto it = solution.begin(); it != solution.end(); it++)
std::cout << it->first << " - " << it->second << std::endl;
}
int main(int argc, char const *argv[])
{
int array[] = {5, 0, 2, 4, 7, 3};
int N = sizeof(array) / sizeof(int);
int S = 7;
set<pair<int, int>> solution;
solve(solution, array, S, N);
printSolution(solution);
return 0;
}