-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathDistinctNumbersOfWindow.java
More file actions
63 lines (52 loc) · 1.32 KB
/
DistinctNumbersOfWindow.java
File metadata and controls
63 lines (52 loc) · 1.32 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package HashMaps;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
* Author - archit.s
* Date - 02/11/18
* Time - 11:03 AM
*/
public class DistinctNumbersOfWindow {
public ArrayList<Integer> dNums(ArrayList<Integer> A, int B) {
ArrayList<Integer> r = new ArrayList<>();
if(B>A.size()){
return r;
}
Map<Integer,Integer> map = new HashMap<>();
int distinct = 0;
int i = 0;
while(i<B){
int value = A.get(i);
if(map.containsKey(value)){
map.put(value,map.get(value)+1);
}
else{
map.put(value,1);
distinct++;
}
i++;
}
r.add(distinct);
while(i<A.size()){
int value = A.get(i-B);
int count = map.getOrDefault(value,0);
if(count==1){
map.put(value,0);
distinct--;
}
else if(count > 1){
map.put(value,count-1);
}
value = A.get(i);
count = map.getOrDefault(value,0);
if(count == 0){
distinct++;
}
map.put(value,count+1);
r.add(distinct);
i++;
}
return r;
}
}