forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
number-of-single-divisor-triplets.cpp
39 lines (38 loc) · 1.38 KB
/
number-of-single-divisor-triplets.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
// Time: O(d^3), d is the number of distinct nums
// Space: O(d)
// combinatorics
class Solution {
public:
long long singleDivisorTriplet(vector<int>& nums) {
const auto& check = [](int a, int b, int c) {
const int total = a + b + c;
return (total % a == 0) + (total % b == 0) + (total % c == 0) == 1;
};
unordered_map<int, int64_t> cnt;
for (const auto& x : nums) {
++cnt[x];
}
vector<int> unique_nums;
for (const auto& [k, _] : cnt) {
unique_nums.emplace_back(k);
}
int64_t result = 0;
for (int i = 0; i < size(unique_nums); ++i) {
for (int j = i + 1; j < size(unique_nums); ++j) {
for (int k = j + 1; k < size(unique_nums); ++k) {
if (check(unique_nums[i], unique_nums[j], unique_nums[k])) {
result += cnt[unique_nums[i]] * cnt[unique_nums[j]] * cnt[unique_nums[k]];
}
}
}
}
for (int i = 0; i < size(unique_nums); ++i) {
for (int j = 0; j < size(unique_nums); ++j) {
if (check(unique_nums[i], unique_nums[i], unique_nums[j])) {
result += cnt[unique_nums[i]] * (cnt[unique_nums[i]] - 1) / 2 * cnt[unique_nums[j]];
}
}
}
return result * 6;
}
};