LC.1054. Distant Barcodes

本文介绍两种重新排列条形码的算法,一种是通过遍历字典选取最大计数的两个元素进行插入,另一种是使用奇偶插入法,先按出现次数排序,再交替插入。后者效率更高。

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

在这里插入图片描述

class Solution1(object):
    def rearrangeBarcodes(self, barcodes):
        """
        每次选出计数最大的两个进行插入,然后将计数器减去1
        该方法每次都要遍历dict会超时
        """
        from collections import defaultdict
        dictionary = defaultdict(int)
        dictionary[-1] = -1
        for num in barcodes:
            dictionary[num] += 1
        res = []

        for _ in range(0,len(barcodes),2):
            max1_key, max2_key = -1,-1
            for key in dictionary:
                if dictionary[key] > dictionary[max1_key]:
                    max2_key = max1_key
                    max1_key = key

                elif dictionary[key] > dictionary[max2_key]:
                    max2_key = key
                else:
                    continue
            dictionary[max1_key] -=1
            dictionary[max2_key] -=1
            res = res + [max1_key, max2_key]
        #当barcodes 为奇数个是会多加一个元素
        if len(barcodes) & 1 == 1:
            return res[:-1]
        else:
            return res


class Solution2(object):
    #奇偶插入法
    #先将数字按照出现次数从大到小排序
    #然后先插入偶数行再插入奇数行
    def rearrangeBarcodes(self, barcodes):
        from collections import Counter
        index = 0
        result = [0] * len(barcodes)
        for number, count in Counter(barcodes).most_common():
            for _ in range(count):
                result[index] = number
                index += 2
                if index >= len(barcodes):
                    index = 1
        return result
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值