-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcountDistinctElementInKWindow.cpp
More file actions
46 lines (39 loc) · 972 Bytes
/
countDistinctElementInKWindow.cpp
File metadata and controls
46 lines (39 loc) · 972 Bytes
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
#include<bits/stdc++.h>
using namespace std;
// Count distint element in every k size window
void naive(vector<int> a, int k){
for(int i = 0; i < a.size()-k+1; i++){
unordered_set<int> s;
for(int j = 0; j < k; j++){
cout << a[i+j] << " ";
s.insert(a[i+j]);
}
cout << '\n' << s.size() << "\n";
}
}
void optimal(vector<int> a, int k){
int n = a.size();
unordered_map<int, int> m;
for(int i = 0; i < k; i++){
m[a[i]]++;
}
cout << m.size() << " ";
for(int i = 1; i < n-k+1; i++){
m[a[i-1]]--;
if(m[a[i-1]] <= 0){
m.erase(m[a[i-1]]);
}
m[a[i+k-1]]++;
cout << m.size() << " ";
}
}
int main(){
vector<int> a = {10, 10, 5, 3, 10, 5};
// vector<int> a = {10, 20, 20, 10, 30, 40, 10};
// vector<int> a = {10, 10, 10, 10};
// int k = 3;
int k = 4;
// ans = 2 3 4 3
optimal(a, k);
return 0;
}