forked from windynight/InterviewPuzzle
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreeSumProblem.cpp
More file actions
64 lines (48 loc) · 1.22 KB
/
Copy pathThreeSumProblem.cpp
File metadata and controls
64 lines (48 loc) · 1.22 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
58
59
60
61
62
63
64
/*
3SUM problem:
Find three number from the given array, whose sum is the given key.
Print all the possible result
Solution:
Time complexity is O(n*n*logn), extra space complexity is O(n)
1. hash all the value of each num in the array
2. for each node a[i], check if there are some pair of numbers whose sum is key - a[i]
PS: as look up in map<int, int> spends O(logn) time complexity,
when hash table is used, the solution's time complexity could be O(n*n)
Sample Input:
5 3
-1 -2 1 2 3
Sample Output:
-1 1 2
-2 2 3
*/
#include <iostream>
#include <map>
using namespace std;
void print3Sum(int a[], int n, int key, int &count)
{
map<int, int> m;
for (int i = 1; i <= n; i ++) {
m[a[i]] = i;
}
for (int i = 1; i <= n; i ++) {
int sum = key - a[i];
for (int j = i + 1; j < n; j ++) {
int tmpSum = sum - a[j];
if (m[tmpSum] && m[tmpSum] != i && m[tmpSum] != j) {
cout << ++ count << ": " << a[i] << ' ' << a[j] << ' ' << tmpSum << endl;
}
}
}
}
int main()
{
int n, key, count;
while (cin >> n >> key && n > 0) {
int a[n + 1];
for (int i = 1; i <= n; i ++) {
cin >> a[i];
}
print3Sum(a, n, key, count);
}
return 0;
}