-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
number-of-divisible-triplet-sums.cpp
60 lines (57 loc) · 1.52 KB
/
number-of-divisible-triplet-sums.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
58
59
60
// Time: O(n^2)
// Space: O(n)
// freq table
class Solution {
public:
int divisibleTripletCount(vector<int>& nums, int d) {
int result = 0;
unordered_map<int, int> cnt;
for (int i = 0; i < size(nums); ++i) {
for (int j = i + 1; j < size(nums); ++j) {
if (cnt.count((nums[i] + nums[j]) % d)) {
result += cnt[(nums[i] + nums[j]) % d];
}
}
++cnt[((-nums[i]) % d + d) % d];
}
return result;
}
};
// Time: O(n^2)
// Space: O(n^2)
// freq table
class Solution2 {
public:
int divisibleTripletCount(vector<int>& nums, int d) {
int result = 0;
unordered_map<int, int> cnt;
for (int i = 0; i < size(nums); ++i) {
if (cnt.count(nums[i] % d)) {
result += cnt[nums[i] % d];
}
for (int j = 0; j < i; ++j) {
++cnt[(-(nums[i] + nums[j]) % d + d) % d];
}
}
return result;
}
};
// Time: O(n^2)
// Space: O(n)
// freq table
class Solution3 {
public:
int divisibleTripletCount(vector<int>& nums, int d) {
int result = 0;
for (int i = 0; i < size(nums); ++i) {
unordered_map<int, int> cnt;
for (int j = i + 1; j < size(nums); ++j) {
if (cnt.count(nums[j] % d)) {
result += cnt[nums[j] % d];
}
++cnt[(-(nums[i] + nums[j]) % d + d) % d];
}
}
return result;
}
};