[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 提供的數據結構比較少,要想實現這個還比較麻煩...我哭哭...

相關文章
相關標籤/搜索