-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1054-distant-barcodes.go
101 lines (92 loc) · 2.21 KB
/
1054-distant-barcodes.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// Link: https://leetcode.com/problems/distant-barcodes/
// SOLUTION 1: using HashMap and if there always has an answer, we fill barcodes every 2 distance
func rearrangeBarcodes(barcodes []int) []int {
hmap := make(map[int]int)
maxBCFreq := 0
mostBC := barcodes[0]
ans := make([]int, len(barcodes))
for _, bc := range barcodes {
if _, ok := hmap[bc]; !ok {
hmap[bc] = 1
} else {
hmap[bc]++
}
if hmap[bc] > maxBCFreq {
maxBCFreq = hmap[bc]
mostBC = bc
}
}
i := 0
idx := 0
// The most frequent barcodes will appear no more than n/2 + 1
for i < maxBCFreq && idx < len(barcodes) {
ans[idx] = mostBC
idx+=2
i++
}
delete(hmap, mostBC)
for k, v := range hmap {
for j:=0; j<v; j++ {
if idx >= len(barcodes) {
idx = 1
}
ans[idx] = k
idx += 2
}
}
return ans
}
// Time complexity: O(N)
// Space complexity: O(N)
// SOLUTION 2: using Priority Queue
import (
"container/heap"
)
type PriorityQueue [][]int
func (pq *PriorityQueue) Len() int {
return len(*pq)
}
func (pq *PriorityQueue) Swap(i,j int) {
(*pq)[i], (*pq)[j] = (*pq)[j], (*pq)[i]
}
func (pq *PriorityQueue) Less(i, j int) bool {
return (*pq)[i][1] > (*pq)[j][1]
}
func (pq *PriorityQueue) Push(k interface{}) {
*pq = append(*pq, k.([]int))
}
func (pq *PriorityQueue) Pop() interface{} {
n := len(*pq)
k := (*pq)[n-1]
*pq = (*pq)[:n-1]
return k
}
func rearrangeBarcodes(barcodes []int) []int {
hmap := make(map[int]int)
ans := make([]int, len(barcodes))
for _, bc := range barcodes {
if _, ok := hmap[bc]; !ok {
hmap[bc] = 1
} else {
hmap[bc]++
}
}
pq := &PriorityQueue{}
heap.Init(pq)
for k, v := range hmap {
heap.Push(pq, []int{k, v})
}
idx := 0
for len(*pq) > 0 {
val := heap.Pop(pq)
bcode := val.([]int)
for c:=0; c<bcode[1]; c++ {
if idx >= len(barcodes) {
idx = 1
}
ans[idx] = bcode[0]
idx+=2
}
}
return ans
}