一、Problem
在一個倉庫裏,有一排條形碼,其中第 i 個條形碼爲 barcodes[i]。
請你重新排列這些條形碼,使其中兩個相鄰的條形碼 不能 相等。 你可以返回任何滿足該要求的答案,此題保證存在答案。
示例 1:
輸入:[1,1,1,2,2,2]
輸出:[2,1,2,1,2,1]
示例 2:
輸入:[1,1,2]
輸出:[1,2,1]
提示:
1 <= barcodes.length <= 10000
1 <= barcodes[i] <= 10000
二、Solution
方法一:大根堆
對於一排空位,怎麼填才能確保相鄰位置不同呢?最直觀的思路就是先隔空填好出現次數多的,然後再填出現次數次多的。
細節:這個隔空的位置需要想一下:每兩個相同的數字 v 都隔開一個位置 i = i+2,越界之後 一定表示這個數字 v 已經被填完了,因爲題目保證存在答案,當 i 越界之後,下一個要填充數字的位置一定是從第一個位置之後開始
class Solution {
public int[] rearrangeBarcodes(int[] bs) {
int n = bs.length;
Map<Integer, Integer> mp = new HashMap<>();
for (int b : bs) mp.put(b, mp.getOrDefault(b, 0) + 1);
Queue<Pair> q = new PriorityQueue<>((e1, e2) -> mp.get(e2.v) - mp.get(e1.v));
mp.forEach((k, v) -> {
q.add(new Pair(k, v));
});
int ans[] = new int[n], i = 0;
while (!q.isEmpty()) {
var cur = q.poll();
for (int j = 0; j < cur.c; j++) {
ans[i] = cur.v;
i = i + 2 >= n ? 1 : i+2;
}
}
return ans;
}
class Pair{
int v, c;
Pair(int v, int c) {this.v = v;this.c = c;}
}
}
複雜度分析
- 時間複雜度:,
- 空間複雜度:,