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 提供的数据结构比较少,要想实现这个还比较麻烦...我哭哭...