# leetcode:距離相等的條形碼

### 題目描述:

============================================================

=========================================================

### java算法

#### 回溯算法

``````class Solution {
//使用回溯法構建
boolean find = false;
private void construct(Map<Integer, Integer> map, int[]barcodes, int i){
if(find)
return;
if(i == barcodes.length){
find = true;
return;
}

for(int key: map.keySet()){
if(map.get(key) > 0 && !find){
if(i == 0 || barcodes[i-1] != key){
barcodes[i] = key;
map.put(key, map.get(key)-1);
construct(map, barcodes, i+1);
map.put(key, map.get(key) + 1);
}
}
}
}

public int[] rearrangeBarcodes(int[] barcodes) {
Map<Integer, Integer> map = new HashMap<>();
for(int i: barcodes){
map.put(i,
map.getOrDefault(i, 0)+1);
}
int[] rearrange = new int[barcodes.length];

construct(map, rearrange, 0);
return rearrange;
}
}
``````

#### 基於最大優先隊列

``````import java.util.AbstractMap.SimpleEntry;

class Solution {
//由於java的優先隊列默認爲最小優先隊列，因此我們需要自定義比較器
class EntryCompare implements Comparator<Map.Entry<Integer, Integer>>{
public int compare(Map.Entry<Integer, Integer> a, Map.Entry<Integer, Integer> b){
return Integer.compare(b.getValue(), a.getValue());
}
}

public int[] rearrangeBarcodes(int[] barcodes) {
HashMap<Integer, Integer> map = new HashMap<>();
for(int val : barcodes)
map.put(val, map.getOrDefault(val,0)+1);

PriorityQueue<Map.Entry<Integer, Integer>> pq = new PriorityQueue<>(10, new EntryCompare());
for (Map.Entry<Integer, Integer> entry: map.entrySet())
pq.offer(entry);

int[] rearrange = new int[barcodes.length];
int i = 0;

if(map.size() == 1)
rearrange[i++] = pq.poll().getKey();
while(i < barcodes.length){
Map.Entry<Integer, Integer> m1 = pq.poll();
Map.Entry<Integer, Integer> m2 = pq.poll();
rearrange[i++] = m1.getKey();
if(i < barcodes.length)
rearrange[i++] = m2.getKey();
pq.offer(new SimpleEntry<Integer, Integer>(m1.getKey(), m1.getValue()-1));
pq.offer(new SimpleEntry<Integer, Integer>(m2.getKey(), m2.getValue()-1));
}
return rearrange;

}
}
``````