1054. Distant Barcodes

18 篇文章 0 订阅
16 篇文章 0 订阅

In a warehouse, there is a row of barcodes, where the i-th 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.

 

Example 1:

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:

  1. 1 <= barcodes.length <= 10000
  2. 1 <= barcodes[i] <= 10000

思路:跟621. Task Scheduler 差不多,priority queue + greedy取出剩余数目最多的数

from collections import Counter
import heapq

class Solution(object):
    def rearrangeBarcodes(self, barcodes):
        """
        :type barcodes: List[int]
        :rtype: List[int]
        """
        d=Counter(barcodes)
        pq=[]
        for k in d: heapq.heappush(pq,(-d[k],k))
        
        res=[]
        while len(res)!=len(barcodes):
            ma,k=heapq.heappop(pq)
            if res and k==res[-1]:
                ma2,k2=heapq.heappop(pq)
                res.append(k2)
                heapq.heappush(pq,(ma2+1,k2))
                heapq.heappush(pq,(ma,k))
            else:
                res.append(k)
                heapq.heappush(pq,(ma+1,k))
        return res
    

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值