-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathDistinctElementsInWindow.java
More file actions
44 lines (40 loc) · 1.01 KB
/
DistinctElementsInWindow.java
File metadata and controls
44 lines (40 loc) · 1.01 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
36
37
38
39
40
41
42
43
44
import java.util.HashMap;
/**
*
* Ashish Patel
* e: ashishsushilPatel@gmail.com
* w: https://ashish.me
*
*/
class DistinctElementsInWindow {
static void printDistinct(int nums[], int k) {
HashMap<Integer, Integer> hm = new HashMap<>();
for(int i = 0; i < k ; i++){
if(hm.containsKey(nums[i])){
hm.put(nums[i], hm.get(nums[i]) + 1);
} else {
hm.put(nums[i], 1);
}
}
System.out.println("Distinct Elements - " + hm.size());
for(int i = k; i < nums.length; i++){
if(hm.containsKey(nums[i-k])){
hm.put(nums[i-k], hm.get(nums[i-k]) - 1);
}
if(hm.get(nums[i-k]) == 0){
hm.remove(nums[i-k]);
}
if(hm.containsKey(nums[i])){
hm.put(nums[i], hm.get(nums[i]) + 1);
} else {
hm.put(nums[i], 0);
}
System.out.println("Distinct Elements - " + hm.size());
}
}
public static void main(String[] args){
int arr[] = new int[]{10, 10, 5, 3, 20, 5};
int k=4;
printDistinct(arr, k);
}
}