forked from kamyu104/LintCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
triangle-count.cpp
57 lines (51 loc) · 1.2 KB
/
triangle-count.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// Time: O(n^2)
// Space: O(1)
// Two Pointers solution.
class Solution {
public:
/**
* @param S: A list of integers
* @return: An integer
*/
int triangleCount(vector<int> &S) {
sort(S.begin(), S.end());
const int n = S.size();
int count = 0;
for (int k = n - 1; k > 1; --k) {
int i = 0, j = k - 1;
while (i < j) { // Two Pointers, linear time.
if (S[i] + S[j] <= S[k]) {
++i;
} else {
count += j - i;
--j;
}
}
}
return count;
}
};
// Time: O(n^3)
// Space: O(1)
class Solution2 {
public:
/**
* @param S: A list of integers
* @return: An integer
*/
int triangleCount(vector<int> &S) {
sort(S.begin(), S.end());
const int n = S.size();
int count = 0;
for (int i = 0; i < n - 2; ++i) {
int k = i + 2;
for (int j = i + 1; j < n; ++j) {
while (k < n && S[i] + S[j] > S[k]) {
++k;
}
count += k - j - 1;
}
}
return count;
}
};