-
Notifications
You must be signed in to change notification settings - Fork 45
/
_1054.java
46 lines (41 loc) · 1.12 KB
/
_1054.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
import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;
/**
* Leetcode 1054 - Distant Barcodes
*
* Greedy using PriorityQueue
*/
public class _1054 {
public int[] rearrangeBarcodes(int[] barcodes) {
int[] f = new int[11111];
for (int i : barcodes) {
f[i]++;
}
int len = 0;
PriorityQueue<Integer> queue = new PriorityQueue<>(Comparator.<Integer>comparingInt(i -> f[i]).reversed().thenComparingInt(i -> i));
for (int i = 0; i < f.length; i++) {
if (f[i] > 0) {
queue.add(i);
}
}
while (true) {
int a = queue.poll();
if (queue.isEmpty()) {
barcodes[len++] = a;
break;
}
int b = queue.poll();
int which = len == 0 || barcodes[len - 1] != a ? a : b;
barcodes[len++] = which;
f[which]--;
if (f[a] > 0) {
queue.add(a);
}
if (f[b] > 0) {
queue.add(b);
}
}
return barcodes;
}
}