-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCount Distinct elements.java
More file actions
35 lines (33 loc) · 1.13 KB
/
Count Distinct elements.java
File metadata and controls
35 lines (33 loc) · 1.13 KB
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
import java.io.*; // for handling input/output
import java.util.*; // contains Collections framework
// don't change the name of this class
// you can add inner classes if needed
class Main {
static void countDistinct(int arr[], int K){
HashMap<Integer, Integer> hM
= new HashMap<Integer, Integer>();
for (int i = 0; i < K; i++)
hM.put(arr[i], hM.getOrDefault(arr[i], 0) + 1);
System.out.print(hM.size() + " ");
for (int i = K; i < arr.length; i++) {
if (hM.get(arr[i - K]) == 1) {
hM.remove(arr[i - K]);
}
else
hM.put(arr[i - K], hM.get(arr[i - K]) - 1);
hM.put(arr[i], hM.getOrDefault(arr[i], 0) + 1);
System.out.print(hM.size() + " ");
}
}
public static void main (String[] args) {
// Your code here
Scanner sc = new Scanner(System.in);
int n =sc.nextInt();
int k = sc.nextInt();
int arr[] = new int[n];
for(int i=0; i<n; i++){
arr[i] = sc.nextInt();
}
countDistinct(arr,k);
}
}