-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathCountDistinctElementInEveryWindow.java
42 lines (38 loc) · 1.21 KB
/
CountDistinctElementInEveryWindow.java
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
package SummerTrainingGFG.Hashing;
import java.util.HashMap;
/**
* @author Vishal Singh
*/
public class CountDistinctElementInEveryWindow {
static void countDistinctElementInEveryWindow(int[] arr,int n,int k){
int totalWindow = n-k+1;
HashMap<Integer, Integer> hashMap = new HashMap<>();
for (int i = 0; i < k; i++) {
if (hashMap.containsKey(arr[i])){
hashMap.put(arr[i],hashMap.get(arr[i])+1);
}
else
hashMap.put(arr[i],1);
}
System.out.print(hashMap.size()+" ");
for (int i = k; i < n; i++) {
if (hashMap.get(arr[i-k]) == 0){
hashMap.remove(arr[i-k]);
}
else
hashMap.put(arr[i-k],hashMap.get(arr[i-k])-1);
if (hashMap.containsKey(arr[i])){
hashMap.put(arr[i],hashMap.get(arr[i])+1);
}
else {
hashMap.put(arr[i],1);
}
System.out.print(hashMap.size()+" ");
}
}
public static void main(String[] args) {
int[] arr = {10,20,20,10,30,40,10};
int k = 4;
countDistinctElementInEveryWindow(arr,arr.length,k);
}
}