LeetCode 1054. Distant Barcodes
考点 | 难度 |
---|---|
Greedy | Easy |
题目
In a warehouse, there is a row of barcodes, where the ith 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.
思路
根据出现次数sort,把最常见的数隔一位放一个。
答案
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