In a warehouse, there is a row of barcodes, where the ith
barcode is barcodes[i]
.
Rearrange the barcodes so that no two adjacent barcodes are equal. You may return any answer, and it is guaranteed an answer exists.
Example 1:
Input: barcodes = [1,1,1,2,2,2] Output: [2,1,2,1,2,1]
Example 2:
Input: barcodes = [1,1,1,1,2,2,3,3] Output: [1,3,1,3,1,2,1,2]
Constraints:
1 <= barcodes.length <= 10000
1 <= barcodes[i] <= 10000
题目链接:https://leetcode.com/problems/distant-barcodes/
题目大意:重排数组使相邻元素不等,保证有解
题目分析:因为保证有解,可以省去一些不必要的判断,分奇偶位放数字,容易想到最优的方案是先选频数大的数字放
17ms,时间击败92.66%
class Solution {
class Data {
int freq, val;
Data(int freq, int val) {
this.freq = freq;
this.val = val;
}
}
public int[] rearrangeBarcodes(int[] barcodes) {
int[] ans = new int[barcodes.length];
int[] cnt = new int[10001];
int sz = 0;
for (int num : barcodes) {
if (cnt[num] == 0) {
sz++;
}
cnt[num]++;
}
Data[] d = new Data[sz];
sz = 0;
for (int num = 1; num < 10001; num++) {
if (cnt[num] != 0) {
d[sz++] = new Data(cnt[num], num);
}
}
Arrays.sort(d, (Data a, Data b) -> (b.freq - a.freq));
// for (int j = 0; j < sz; j++) {
// System.out.println(d[j].val + " " + d[j].freq);
// }
int i = 0, idx = 0;
while (i < sz) {
if (idx >= barcodes.length) {
idx = 1;
}
if (d[i].freq == 0) {
i++;
}
if (i < sz) {
ans[idx] = d[i].val;
d[i].freq--;
idx += 2;
}
}
return ans;
}
}