Leetcode 1054. Distant Barcodes(K Distance Apart Question)

本文解析了LeetCode1054.DistantBarcodes问题,提出了一种有效的解决策略,通过统计仓库编号出现次数并间隔排列,确保任意两个相邻编号不同。类似于LeetCode767.ReorganizeString,适用于中等难度算法题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值