website/content.en/ChapterFour/1000~1099/1054.Distant-Barcodes.md
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 1:
Input: [1,1,1,2,2,2]
Output: [2,1,2,1,2,1]
Example 2:
Input: [1,1,1,1,2,2,3,3]
Output: [1,3,1,3,2,1,2,1]
Note:
1 <= barcodes.length <= 100001 <= barcodes[i] <= 10000In a warehouse, there is a row of barcodes, where the i-th barcode is barcodes[i]. Please rearrange these barcodes so that no two adjacent barcodes are equal. You may return any answer that satisfies the requirement, and it is guaranteed that an answer exists.
package leetcode
import "sort"
func rearrangeBarcodes(barcodes []int) []int {
bfs := barcodesFrequencySort(barcodes)
if len(bfs) == 0 {
return []int{}
}
res := []int{}
j := (len(bfs)-1)/2 + 1
for i := 0; i <= (len(bfs)-1)/2; i++ {
res = append(res, bfs[i])
if j < len(bfs) {
res = append(res, bfs[j])
}
j++
}
return res
}
func barcodesFrequencySort(s []int) []int {
if len(s) == 0 {
return []int{}
}
sMap := map[int]int{} // Count the frequency of each number
cMap := map[int][]int{} // Sort using the frequency as the key
for _, b := range s {
sMap[b]++
}
for key, value := range sMap {
cMap[value] = append(cMap[value], key)
}
var keys []int
for k := range cMap {
keys = append(keys, k)
}
sort.Sort(sort.Reverse(sort.IntSlice(keys)))
res := make([]int, 0)
for _, k := range keys {
for i := 0; i < len(cMap[k]); i++ {
for j := 0; j < k; j++ {
res = append(res, cMap[k][i])
}
}
}
return res
}