-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathcount-special-subsequences.cpp
44 lines (42 loc) · 1.26 KB
/
count-special-subsequences.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
// Time: O(n^2)
// Space: O(n^2)
// freq table
class Solution {
public:
long long numberOfSubsequences(vector<int>& nums) {
int64_t result = 0;
unordered_map<double, int> cnt;
for (int r = 4; r + 2 < size(nums); ++r) {
const int q = r - 2;
for (int p = 0; p <= q - 2; ++p) {
++cnt[static_cast<double>(nums[p]) / nums[q]];
}
for (int s = r + 2; s < size(nums); ++s) {
result += cnt[static_cast<double>(nums[s]) / nums[r]];
}
}
return result;
}
};
// Time: O(n^2 * logr)
// Space: O(n^2)
// freq table, number theory
class Solution2 {
public:
long long numberOfSubsequences(vector<int>& nums) {
int64_t result = 0;
unordered_map<int, unordered_map<int, int>> cnt;
for (int r = 4; r + 2 < size(nums); ++r) {
const int q = r - 2;
for (int p = 0; p <= q - 2; ++p) {
const int g = gcd(nums[p], nums[q]);
++cnt[nums[p] / g][nums[q] / g];
}
for (int s = r + 2; s < size(nums); ++s) {
const int g = gcd(nums[s], nums[r]);
result += cnt[nums[s] / g][nums[r] / g];
}
}
return result;
}
};