【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