forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDistant Barcodes.java
47 lines (38 loc) · 1.27 KB
/
Distant Barcodes.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
43
44
45
46
47
class Solution {
public int[] rearrangeBarcodes(int[] barcodes) {
if(barcodes.length <= 2){
return barcodes ; //Problem says solution always exist.
}
Map<Integer, Integer> count = new HashMap<>();
Integer maxKey = null; // Character having max frequency
for(int i: barcodes){
count.put(i, count.getOrDefault(i, 0) + 1);
if(maxKey == null || count.get(i) > count.get(maxKey)){
maxKey = i;
}
}
int pos = 0;
//Fill maxChar
int curr = count.get(maxKey);
while(curr-- > 0){
barcodes[pos] = maxKey;
pos += 2;
if(pos >= barcodes.length){
pos = 1;
}
}
count.remove(maxKey); // Since that character is done, we don't need to fill it again
//Fill the remaining Characters.
for(int key: count.keySet()){
curr = count.get(key);
while(curr-- > 0){
barcodes[pos] = key;
pos += 2;
if(pos >= barcodes.length){
pos = 1;
}
}
}
return barcodes;
}
}