【
在一个仓库里,有一排条形码,其中第 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
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/distant-barcodes
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
】
1. 见到数组先考虑排序,排序方式时按照次数排序,让人想到哈希
2. 不重复,那么先放偶数,再放奇数位置
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
typedef struct {
int key;
int val;
UT_hash_handle hh;
} UTHASH;
int Cmp(UTHASH *a, UTHASH *b) {
return b->val - a->val;
}
int* rearrangeBarcodes(int* barcodes, int barcodesSize, int* returnSize){
UTHASH *mymap = NULL;
int i;
int idx = 0;
int *retarr = malloc(sizeof(int) * barcodesSize);
for (i = 0; i < barcodesSize; i++) {
UTHASH *find = NULL;
HASH_FIND_INT(mymap, &barcodes[i], find);
if (find != NULL) {
find->val += 1;
} else {
UTHASH *new = malloc(sizeof(UTHASH));
new->key = barcodes[i];
new->val = 1;
HASH_ADD_INT(mymap, key, new);
}
}
HASH_SORT(mymap, Cmp);
UTHASH *cur, *tmp;
HASH_ITER(hh, mymap, cur, tmp) { // 遍历HASH表
while (cur->val > 0) { // 当前元素没有使用完时
retarr[idx] = cur->key; // 把元素放入retarr
idx = idx + 2; // idx 跳着放,即先填偶数位
if (idx >= barcodesSize) { // 如果idx 到达retarr尾部
idx = 1; // 开始填奇数位
}
cur->val--; // 每次放一个元素,元素的个数减一
}
}
*returnSize = barcodesSize;
return retarr;
}
/*
1. 见到数组先考虑排序,排序方式时按照次数排序,让人想到哈希
2. 不重复,那么先放偶数,再放奇数位置
*/