-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.go
69 lines (57 loc) · 1.19 KB
/
Solution.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
package lc506
import (
"container/heap"
"strconv"
)
func findRelativeRanks(score []int) []string {
comparator := func(i int, j int) bool {
return score[i] > score[j]
}
indices := make([]int, len(score))
for i := range score {
indices[i] = i
}
pq := &IntPriorityQueue{
values: indices,
comp: comparator,
}
heap.Init(pq)
ranks := make([]string, len(score))
for i := range len(score) {
idx := heap.Pop(pq).(int)
switch i {
case 0:
ranks[idx] = "Gold Medal"
case 1:
ranks[idx] = "Silver Medal"
case 2:
ranks[idx] = "Bronze Medal"
default:
ranks[idx] = strconv.Itoa(i + 1)
}
}
return ranks
}
type IntPriorityQueue struct {
values []int
comp func(i int, j int) bool
}
func (pq IntPriorityQueue) Len() int {
return len(pq.values)
}
func (pq IntPriorityQueue) Less(i int, j int) bool {
return pq.comp(pq.values[i], pq.values[j])
}
func (pq IntPriorityQueue) Swap(i int, j int) {
pq.values[i], pq.values[j] = pq.values[j], pq.values[i]
}
func (pq *IntPriorityQueue) Push(x any) {
pq.values = append(pq.values, x.(int))
}
func (pq *IntPriorityQueue) Pop() any {
old := pq.values
n := len(old)
item := old[n-1]
pq.values = old[0 : n-1]
return item
}