LeetCode 1054. 距离相等的条形码(优先队列)
发布日期:2021-07-01 03:20:22 浏览次数:2 分类:技术文章

本文共 1296 字,大约阅读时间需要 4 分钟。

1. 题目

在一个仓库里,有一排条形码,其中第 i 个条形码为 barcodes[i]。

请你重新排列这些条形码,使其中两个相邻的条形码 不能 相等。 你可以返回任何满足该要求的答案,此题保证存在答案。

示例 1:输入:[1,1,1,2,2,2]输出:[2,1,2,1,2,1]示例 2:输入:[1,1,1,1,2,2,3,3]输出:[1,3,1,3,2,1,2,1] 提示:1 <= barcodes.length <= 100001 <= barcodes[i] <= 10000

来源:力扣(LeetCode)

链接:https://leetcode-cn.com/problems/distant-barcodes
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2. 解题

  • 对数字计数
  • 插入优先队列,数量多的先出队
  • 从0开始隔一个插入一个,然后从1开始插空
class Solution {
struct cmp {
bool operator()(pair
& a, pair
& b) {
return a.second < b.second;}//小就是大顶堆 };public: vector
rearrangeBarcodes(vector
& barcodes) {
if(barcodes.size() <= 2) return barcodes; int n = barcodes.size(), i = 0, tpnum, tpcount; bool reachEnd = false; unordered_map
m; for(auto& b : barcodes) m[b]++;//计数 priority_queue
, vector
>,cmp> q; for(auto& mi : m) q.push(mi); vector
ans(n,0); while(!q.empty()) { tpnum = q.top().first; tpcount = q.top().second; q.pop(); while(i < n && !reachEnd && tpcount) { while(i < n && tpcount) { ans[i] = tpnum; tpcount--; i += 2; } if(i >= n) { reachEnd = true;//到达末尾了 i = 1;//填写偶数位 } } while(i < n && tpcount) { ans[i] = tpnum; tpcount--; i += 2; } } return ans; }};

在这里插入图片描述

转载地址:https://michael.blog.csdn.net/article/details/104317529 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:剑指Offer - 面试题22. 链表中倒数第k个节点(快慢指针)
下一篇:程序员面试金典 - 面试题 17.11. 单词距离(multimap平衡二叉搜索树)

发表评论

最新留言

表示我来过!
[***.240.166.169]2024年04月25日 07时49分57秒