[LeetCode] 1054. Distant Barcodes

原版题目:

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

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:bash

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:this

1 <= barcodes.length <= 10000
1 <= barcodes[i] <= 10000
复制代码

hint:spa

We want to always choose the most common or second most common element to write next. What data structure allows us to query this effectively?code

优质解答

代码来源ip

class Solution(object):
    def rearrangeBarcodes(self, packages):
        i, n = 0, len(packages)
        res = [0] * n
        for k, v in collections.Counter(packages).most_common():
            for _ in xrange(v):
                res[i] = k
                i += 2
                if i >= n: i = 1
        return res
复制代码

解析

  • 关键点 1: 如何重排element

    • 要将数组中全部数字,按照其出现次数的多少顺序排列。
  • 关键点 2: 如何组合leetcode

    • 方法 1: 老是优先将出现次数最多或者第二多的数字插入重组的数组
    • 方法 2: 间隔一位插入数字,也就是上面解答中的方式,因为题目保证必定有一个解,因此这种方式也是可行的。

...小声 bb:哎呀果真 python 大法好...JavaScript 提供的数据结构比较少,要想实现这个还比较麻烦...我哭哭...

相关文章
相关标签/搜索