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
...小聲 bb:哎呀果真 python 大法好...JavaScript 提供的數據結構比較少,要想實現這個還比較麻煩...我哭哭...