免费建设网站c3sales百度推广好不好做
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:vector<int> rearrangeBarcodes(vector<int>& barcodes) {unordered_map<int,int> number_time;vector<int> result;for(auto x:barcodes)number_time[x]++;priority_queue<pair<int,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();// cout<<now.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.first>0)members.push(nowNext);}if(now.first>0)members.push(now);// cout<<"resultSize:"<<result.size()<<endl;}return result;}
};
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/squares-of-a-sorted-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。