Leetcode 1054. Distant Barcodes
题目链接: Distant Barcodes
难度:Medium
题目大意:
输入一组数代表各个仓库的编号,这些编号中有重复的,要求将这些编号进行排列,使得任意两个相邻的仓库编号不同。这道题与Leetcode 767 Reorganize String 相似。
可参看我的另一篇博客Leetcode 767. Reorganize String(容易理解的解法)
思路:
因为题目说了不存在某种方案不满足题意,所以不考虑什么情况才有解。统计各个编号出现的次数,先间隔安放出现次数的编号(下标分别为0,2,4……),再安放剩余其他编号,也是间隔排列,保证相邻的两个编号不同。
也有大佬把这题归为K Distance Apart Question where K = 2
参看高赞回答。
代码
class Solution {
public int[] rearrangeBarcodes(int[] barcodes) {
Map<Integer,Integer> map=new HashMap<>();
int mostCode=barcodes[0];//出现次数最多的编号
for(int n:barcodes){
map.put(n,map.getOrDefault(n,0)+1);//统计各个编号的个数
}
for(Integer key:map.keySet()){//找出出现次数最多的编号
if(map.get(key)>map.get(mostCode)){
mostCode=key;
}
}
int i=0;
int[] res=new int[barcodes.length];
int num=map.get(mostCode);//注意把Integer转成int
while(num-->0){
res[i]=mostCode;
map.put(mostCode,map.get(mostCode)-1);
i+=2;
}
for(Integer key:map.keySet()){
num=map.get(key);
while(num-->0){
if(i>=res.length){
i=1;
}
res[i]=key;
i+=2;
}
}
return res;
}
}