1054 Distant Barcodes

Distant Barcodes

1
2
3
4
5
6
In a warehouse, there is a row of barcodes, where the i-th barcode is barcodes[i].

Rearrange the barcodes so that no two adjacent barcodes are equal. You may return any answer, and it is guaranteed an answer exists.
Example:
Input: [1,1,1,2,2,2]
Output: [2,1,2,1,2,1]

让数组中相邻的数字不相同,题目保证了一定存在。让数组中出现次数最多的那个数字跟出现次数第二多的数字交叉排列(这里可以直接放到奇数位,然后放到偶数位,就可以一次只取出一种数字)。排完之后排紧接着排下一个频率最多的。

讨论区里:只需要先排列频率最多的就行了,其他的数字顺序可以随意。

重点:直接放到偶数位上,满了之后再放到奇数位,不要挨着一个交替一个放,这样就不用考虑重复的问题。