-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathThreeSum.h
73 lines (67 loc) · 2.05 KB
/
ThreeSum.h
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
#ifndef CH1_THREESUM_H
#define CH1_THREESUM_H
#include <vector>
#include <iostream>
using std::vector;
using std::cout;
using std::endl;
/**
* The {@code ThreeSum} class provides static methods for counting
* and printing the number of triples in an array of integers that sum to 0
* (ignoring integer overflow).
* <p>
* This implementation uses a triply nested loop and takes proportional to n^3,
* where n is the number of integers.
* <p>
* For additional documentation, see <a href="https://algs4.cs.princeton.edu/14analysis">Section 1.4</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
class ThreeSum {
public:
// Do not instantiate.
ThreeSum() = delete;
/**
* Prints to standard output the (i, j, k) with {@code i < j < k}
* such that {@code a[i] + a[j] + a[k] == 0}.
*
* @param a the array of integers
*/
static void printAll(vector<int> &a) {
int n = a.size();
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
for (int k = j + 1; k < n; k++) {
if (a[i] + a[j] + a[k] == 0) {
cout << a[i] << " " << a[j] << " " << -(a[i] + a[j]) << endl;
}
}
}
}
}
/**
* Returns the number of triples (i, j, k) with {@code i < j < k}
* such that {@code a[i] + a[j] + a[k] == 0}.
*
* @param a the array of integers
* @return the number of triples (i, j, k) with {@code i < j < k}
* such that {@code a[i] + a[j] + a[k] == 0}
*/
static int count(vector<int> &a) {
int n = a.size();
int count = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
for (int k = j + 1; k < n; k++) {
if (a[i] + a[j] + a[k] == 0) {
count++;
}
}
}
}
return count;
}
};
#endif //CH1_THREESUM_H