【leetcode】1054. Distant Barcodes

题目如下:

In a warehouse, there is a row of barcodes, where the i-th barcode is barcodes[i].

Rearrange the barcodes so that no two adjacent barcodes are equal.  You may return any answer, and it is guaranteed an answer exists.

 

Example 1:

Input: [1,1,1,2,2,2]
Output: [2,1,2,1,2,1]

Example 2:

Input: [1,1,1,1,2,2,3,3]
Output: [1,3,1,3,2,1,2,1]

 

Note:

  1. 1 <= barcodes.length <= 10000
  2. 1 <= barcodes[i] <= 10000

解题思路:首先把input按元素出现的次数从多到少排序,如果出现的次数一样,可以按值从小到大排好序。接下来遍历input,依次pop出input的第一个元素,并且把这个元素放入Output的奇数位上;完成之后再依次pop出input的第一个元素并放入Output的偶数位。

代码如下:

class Solution(object):
    def rearrangeBarcodes(self, barcodes):
        """
        :type barcodes: List[int]
        :rtype: List[int]
        """
        dic = {}
        for i in barcodes:
            if i not in dic:
                dic[i] = [i,1]
            else:
                dic[i][1] += 1

        def cmpf(l1,l2):
            if l1[1] != l2[1]:
                return l2[1] - l1[1]
            return l1[0] - l2[0]

        tmp_list = sorted(dic.itervalues(),cmp=cmpf)

        blist = []
        for (k,v) in tmp_list:
            blist += [k] * v

        res = [0] * len(barcodes)
        for i in range(0,len(res),2):
            res[i] = blist.pop(0)
        for i in range(1,len(res), 2):
            res[i] = blist.pop(0)
        return res

 

转载于:https://www.cnblogs.com/seyjs/p/10930581.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值