在一个仓库里,有一排条形码,其中第 i
个条形码为 barcodes[i]
。
请你重新排列这些条形码,使其中任意两个相邻的条形码不能相等。 你可以返回任何满足该要求的答案,此题保证存在答案。
示例 1:
输入:barcodes = [1,1,1,2,2,2] 输出:[2,1,2,1,2,1]
示例 2:
输入:barcodes = [1,1,1,1,2,2,3,3] 输出:[1,3,1,3,2,1,2,1]
解法:贪心+模拟
1.每次处理一批相同的数。
2.摆放的时候,每次隔一个格子。
3。先处理出现次数最多的那个数,剩下的处理顺序无所谓;
import java.util.HashMap;
import java.util.Map;
public class Solution {public int[] rearrangeBarcodes(int[] barcodes) {Map<Integer,Integer>hash=new HashMap<>();//统计每个数字出现了多少次int maxVal=0,maxCount=0;for (int x:barcodes){hash.put(x,hash.getOrDefault(x,0)+1);if (maxCount<hash.get(x)){maxVal=x;maxCount=hash.get(x);}}int n= barcodes.length;int[] ret =new int[n];int index=0;//先处理出现次数最多的那个数for (int i=0;i<maxCount;i++){ret[index]=maxVal;index +=2;}hash.remove(maxVal);for (int x:hash.keySet()){for (int i=0;i<hash.get(x);i++){if (index>=n)index=1;ret[index]=x;index +=2;}}return ret;}public static void main(String[] args) {Solution solution=new Solution();int[] barcodes={1,1,1,1,2,2,3,3};int[] result=solution.rearrangeBarcodes(barcodes);for (int num:result){System.out.print(num+"");}}
}