forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
k-divisible-elements-subarrays.cpp
118 lines (109 loc) · 3.17 KB
/
k-divisible-elements-subarrays.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
// Time: O(n^2)
// Space: O(t), t is the size of trie
// trie
class Solution {
public:
int countDistinct(vector<int>& nums, int k, int p) {
Trie trie;
for (int i = 0; i < size(nums); ++i) {
trie.insert(nums, i, k, p);
}
return trie.count();
}
private:
class Trie {
public:
Trie() : nodes_(1) {
}
void insert(const vector<int>& nums, int i, int k, int p) {
int curr = 0, cnt = 0;
for (int j = i; j < size(nums); ++j) {
cnt += (nums[j] % p == 0);
if (cnt > k) {
break;
}
if (!nodes_[curr].count(nums[j])) {
nodes_[curr][nums[j]] = create_node();
}
curr = nodes_[curr][nums[j]];
}
}
int count() const {
return size(nodes_) - 1;
}
private:
int create_node() {
nodes_.emplace_back();
return size(nodes_) - 1;
}
using TrieNode = unordered_map<int, int>;
vector<TrieNode> nodes_;
};
};
// Time: O(n^2) on average, worst is O(n^3)
// Space: O(n)
// rolling hash
class Solution2 {
public:
int countDistinct(vector<int>& nums, int k, int p) {
static const int MOD = 1e9 + 7;
static const int64_t P = 113;
const auto& check = [&nums](const auto& lookup, int l, int i) {
for (const auto& j : lookup) {
int k = 0;
for (; k < l; ++k) {
if (nums[i + k] != nums[j + k]) {
break;
}
}
if (k == l) {
return false;
}
}
return true;
};
vector<int> cnt(size(nums)), h(size(nums));
int result = 0;
for (int l = 1; l <= size(nums); ++l) {
unordered_map<int, vector<int>> lookup;
for (int i = 0; i + l - 1 < size(nums); ++i) {
cnt[i] += (nums[i + l - 1] % p == 0);
if (cnt[i] > k) {
continue;
}
h[i] = (h[i] * P + nums[i + l - 1]) % MOD;
if (!check(lookup[h[i]], l, i)) {
continue;
}
lookup[h[i]].emplace_back(i);
++result;
}
}
return result;
}
};
// Time: O(n^2)
// Space: O(n)
// rolling hash
class Solution3 {
public:
int countDistinct(vector<int>& nums, int k, int p) {
static const int MOD = 1e9 + 7;
static const int64_t P = 200;
vector<int> cnt(size(nums)), h(size(nums));
int result = 0;
for (int l = 1; l <= size(nums); ++l) {
unordered_set<int> lookup;
for (int i = 0; i + l - 1 < size(nums); ++i) {
cnt[i] += (nums[i + l - 1] % p == 0);
if (cnt[i] > k) {
continue;
}
h[i] = (h[i] * P + nums[i + l - 1]) % MOD;
lookup.emplace(h[i]);
}
result += size(lookup);
}
return result;
}
};