网站建设和维护pdf,网站建设项目实训报告,页面布局标准格式,塘沽网站优化1054. 距离相等的条形码#xff08;leetcode,堆问题#xff0c;priority_queue#xff09;-------------------c实现
题目表述
在一个仓库里#xff0c;有一排条形码#xff0c;其中第 i 个条形码为 barcodes[i]。
请你重新排列这些条形码#xff0c;使其中任意两个相…1054. 距离相等的条形码leetcode,堆问题priority_queue-------------------c实现
题目表述
在一个仓库里有一排条形码其中第 i 个条形码为 barcodes[i]。
请你重新排列这些条形码使其中任意两个相邻的条形码不能相等。 你可以返回任何满足该要求的答案此题保证存在答案。
样例
示例 1
输入barcodes [1,1,1,2,2,2] 输出[2,1,2,1,2,1] 示例 2
输入barcodes [1,1,1,1,2,2,3,3] 输出[1,3,1,3,2,1,2,1]
条件
1 barcodes.length 10000 1 barcodes[i] 10000
思路
先通过unordered_map记录各个数出现的个数然后通过priority进行堆排序每次在可允许输出的情况下(前一个数不是当前最大数||当前为空)先输出最大值。
注意点
ac代码
c:
class Solution {
public:vectorint rearrangeBarcodes(vectorint barcodes) {unordered_mapint,int number_time;vectorint result;for(auto x:barcodes)number_time[x];priority_queuepairint,int members;for(auto x:number_time)members.push({x.second,x.first});while(members.size()){auto now members.top();//answer writing//auto [x,cx] members.top();members.pop();// coutnow.first now.second ;if(result.empty()||now.second!result[result.size()-1])//can sit the biggest member{result.push_back(now.second);now.first--;}else{auto nowNext members.top();members.pop();result.push_back(nowNext.second);nowNext.first--;if(nowNext.first0)members.push(nowNext);}if(now.first0)members.push(now);// coutresultSize:result.size()endl;}return result;}
};来源力扣LeetCode 链接https://leetcode-cn.com/problems/squares-of-a-sorted-array 著作权归领扣网络所有。商业转载请联系官方授权非商业转载请注明出处。