首页 > 其他分享 >距离相等的条形码

距离相等的条形码

时间:2023-05-15 18:57:22浏览次数:28  
标签:条形码 相等 maxNum int barcode 距离 ans barcodes

在一个仓库里,有一排条形码,其中第 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 <= barcodes.length <= 10000
  • 1 <= barcodes[i] <= 10000

来源:力扣(LeetCode)

题解

点击查看代码
class Solution {
    public int[] rearrangeBarcodes(int[] barcodes) {
        // 在排序插入的基础上优化
        // 对出现次数最多的元素来插空
        int len = barcodes.length, maxNum = 0, j = 0;
        //统计元素次数
        int[] ans = new int[10001], res = new int[len];
        //遍历数组提取最多次的元素
        for(int barcode : barcodes){
            if(++ans[barcode] > ans[maxNum]){
                maxNum = barcode;
            }
        }
        //先用次数最多的填充插空
        for(int i = 0; i < 10001; i++){
            int temp = i == 0 ? maxNum : i;
            while(ans[temp]-- > 0){
                res[j] = temp;
                j = j + 2 < len ? j + 2 : 1;
            }
        }
        //返回结果数组
        return res;
    }
}

标签:条形码,相等,maxNum,int,barcode,距离,ans,barcodes
From: https://www.cnblogs.com/wuli-Zhang/p/17402793.html

相关文章