LeetCode每日一题(1054. Distant Barcodes)

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.

Example 1:

Input: barcodes = [1,1,1,2,2,2]
Output: [2,1,2,1,2,1]

Example 2:

Input: barcodes = [1,1,1,1,2,2,3,3]
Output: [1,3,1,3,1,2,1,2]

Constraints:

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

对 barcodes 里相同的数字进行计数, 然后每次挑选数量最多的数字放置到答案中,同时检查该数字是不是答案中前一个数字相同,如果相同则取出数量第二多的数字放到答案中, 放置的数字数量-1



use std::collections::BinaryHeap;

impl Solution {
    pub fn rearrange_barcodes(mut barcodes: Vec<i32>) -> Vec<i32> {
        barcodes.sort();
        let mut heap = BinaryHeap::new();
        let mut prev = barcodes[0];
        let mut count = 1;
        for &code in barcodes[1..].into_iter() {
            if prev != code {
                heap.push((count, prev));
                prev = code;
                count = 1;
                continue;
            }
            count += 1;
        }
        heap.push((count, prev));
        let mut ans = Vec::new();
        while let Some((c, v)) = heap.pop() {
            if let Some(&last) = ans.last() {
                if v == last {
                    let (nc, nv) = heap.pop().unwrap();
                    ans.push(nv);
                    if nc > 1 {
                        heap.push((nc - 1, nv));
                    }
                    heap.push((c, v));
                    continue;
                }
                ans.push(v);
                if c > 1 {
                    heap.push((c - 1, v));
                }
                continue;
            }
            ans.push(v);
            if c > 1 {
                heap.push((c - 1, v));
            }
        }
        ans
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值