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 <= 10000
1 <= barcodes[i] <= 10000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/distant-barcodes
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2. 解题
- 对数字计数
- 插入优先队列,数量多的先出队
- 从0开始隔一个插入一个,然后从1开始插空
class Solution {
struct cmp
{
bool operator()(pair<int,int>& a, pair<int,int>& b)
{return a.second < b.second;}//小就是大顶堆
};
public:
vector<int> rearrangeBarcodes(vector<int>& barcodes) {
if(barcodes.size() <= 2)
return barcodes;
int n = barcodes.size(), i = 0, tpnum, tpcount;
bool reachEnd = false;
unordered_map<int,int> m;
for(auto& b : barcodes)
m[b]++;//计数
priority_queue<pair<int,int>, vector<pair<int,int>>,cmp> q;
for(auto& mi : m)
q.push(mi);
vector<int> 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;
}
};