-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDay 103.java
More file actions
28 lines (22 loc) · 826 Bytes
/
Day 103.java
File metadata and controls
28 lines (22 loc) · 826 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
class Solution {
ArrayList<Integer> countDistinct(int arr[], int k) {
ArrayList<Integer> result = new ArrayList<>();
if (arr == null || arr.length == 0 || k == 0) return result;
HashMap<Integer, Integer> freq = new HashMap<>();
for (int i = 0; i < k; i++) {
freq.put(arr[i], freq.getOrDefault(arr[i], 0) + 1);
}
result.add(freq.size());
for (int i = k; i < arr.length; i++) {
int outgoing = arr[i - k];
freq.put(outgoing, freq.get(outgoing) - 1);
if (freq.get(outgoing) == 0) {
freq.remove(outgoing);
}
int incoming = arr[i];
freq.put(incoming, freq.getOrDefault(incoming, 0) + 1);
result.add(freq.size());
}
return result;
}
}