LC.P1054[距离相等的条形码]

方法一:计数+排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public int[] rearrangeBarcodes(int[] barcodes) {
int n = barcodes.length;
int max = Arrays.stream(barcodes).max().getAsInt();
Integer[] index = new Integer[n];
for (int i = 0; i < n; ++i) {
index[i] = barcodes[i];
}
int[] cnt = new int[max + 1];
for (int x : barcodes) ++cnt[x];
Arrays.sort(index, (a, b) -> cnt[a] == cnt[b] ? a - b : cnt[b] - cnt[a]);
int[] ans = new int[n];
for (int j = 0, k = 0; k < 2; ++k) {
for (int i = k; i < n; i += 2) {
ans[i] = index[j++];
}
}
return ans;
}
}
  • 时间复杂度:$O(nlogn)$
  • 空间复杂度:$O(n)$