In a warehouse, there is a row of barcodes, where the i
-th 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: [1,1,1,2,2,2] Output: [2,1,2,1,2,1]
Example 2:
Input: [1,1,1,1,2,2,3,3] Output: [1,3,1,3,2,1,2,1]
思路:跟 Reorganize String 一模一样;
数学的思想就是,统计频率以后,先用频率最大的填0,2,4 然后继续用c填 6,8,10 ...直到超出length范围,然后从奇数位子开始填1,3,5 这样就是一个不想临的string;我个人比较喜欢后面一种用priorityqueue来解答的,可以拓展到 Rearrange String k Distance Apart 这题,这两题其实非常类似;
class Solution {
public int[] rearrangeBarcodes(int[] barcodes) {
if(barcodes == null || barcodes.length == 0) {
return new int[0];
}
int n = barcodes.length;
int[] res = new int[n];
HashMap<Integer, Integer> countMap = new HashMap<>();
int maxi = 0; int maxcount = 0;
for(int i = 0; i < barcodes.length; i++) {
int val = barcodes[i];
countMap.put(val, countMap.getOrDefault(val, 0) + 1);
if(countMap.get(val) > maxcount) {
maxcount = countMap.get(val);
maxi = val;
}
}
int index = 0;
while(index < n && countMap.get(maxi) > 0) {
res[index] = maxi;
index += 2;
countMap.put(maxi, countMap.get(maxi) - 1);
}
for(Integer i: countMap.keySet()) {
while(countMap.get(i) > 0) {
if(index >= n) {
index = 1;
}
res[index] = i;
index += 2;
countMap.put(i, countMap.get(i) - 1);
}
}
return res;
}
}
用priorityQueue来做,比较规范,最后T: nlog(26) = > O(N);
class Solution {
private class Node {
public int val;
public int fre;
public Node(int val, int fre) {
this.val = val;
this.fre = fre;
}
}
private class NodeComparator implements Comparator<Node> {
@Override
public int compare(Node a, Node b) {
return b.fre - a.fre;
}
}
public int[] rearrangeBarcodes(int[] barcodes) {
if(barcodes == null || barcodes.length == 0) {
return new int[0];
}
int n = barcodes.length;
HashMap<Integer, Integer> countMap = new HashMap<>();
for(int i = 0; i < n; i++) {
int val = barcodes[i];
countMap.put(val, countMap.getOrDefault(val, 0) + 1);
}
PriorityQueue<Node> pq = new PriorityQueue<Node>(new NodeComparator());
for(Integer val: countMap.keySet()) {
pq.offer(new Node(val, countMap.get(val)));
}
int[] res = new int[n];
int index = 0;
Node pre = null;
while(!pq.isEmpty()) {
Node node = pq.poll();
res[index++] = node.val;
node.fre--;
if(pre != null && pre.fre > 0) {
pq.offer(pre);
}
pre = node;
}
return res;
}
}