/*
1、排序数组,使相邻元素不同
2、优先处理频率高的元素
*/
class Solution {
public:
vector<int> rearrangeBarcodes(vector<int>& barcodes) {
int n = barcodes.size();
int temp[10000+1];
memset(temp , 0 , sizeof(temp)); //定义一个临时数组
for(auto it:barcodes) //遍历条形码数组 ,it就是barcodes[i]的值
{
temp[it]++; //表示数字 频率
}
//本题的核心
sort(barcodes.begin(), barcodes.end(), [&](int a, int b){ //按照频率由大到小排序
return (temp[a] > temp[b]) || (temp[a] == temp[b] && a < b);
//返回频率较大的 频率相等时,返回数字较小的
});
vector<int> ans(n); //用于记录最终结果
int j = 0; //j表示barcodes的数据 顺序 放入ans数组中
for(int i = 0 ; i < n ; i+=2) //奇数排放(数字出现的频率最大数也才是数组大小的一半)
{
ans[i] = barcodes[j];
j++;
}
for(int i = 1 ; i < n ; i+=2) //偶数排放
{
ans[i] = barcodes[j];
j++;
}
return ans;
}
};