forked from wufenggirl/LeetCode-in-Golang
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaximum-frequency-stack.go
More file actions
executable file
·77 lines (65 loc) · 1.34 KB
/
maximum-frequency-stack.go
File metadata and controls
executable file
·77 lines (65 loc) · 1.34 KB
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
package problem0895
import (
"container/heap"
)
// FreqStack object will be instantiated and called as such:
// obj := Constructor();
// obj.Push(x);
// param_2 := obj.Pop();
type FreqStack struct {
index int
freq map[int]int
pq *PQ
}
// Constructor 构建 FreqStack
func Constructor() FreqStack {
pq := make(PQ, 0, 10000)
return FreqStack{
freq: make(map[int]int, 10000),
pq: &pq,
}
}
// Push 在 fs 中放入 x
func (fs *FreqStack) Push(x int) {
fs.index++
fs.freq[x]++
e := &entry{
key: x,
index: fs.index,
freq: fs.freq[x],
}
heap.Push(fs.pq, e)
}
// Pop 从 fs 中弹出元素
func (fs *FreqStack) Pop() int {
x := heap.Pop(fs.pq).(*entry).key
fs.freq[x]--
return x
}
// entry 是 priorityQueue 中的元素
type entry struct {
key, index, freq int
}
// PQ implements heap.Interface and holds entries.
type PQ []*entry
func (pq PQ) Len() int { return len(pq) }
func (pq PQ) Less(i, j int) bool {
if pq[i].freq == pq[j].freq {
return pq[i].index > pq[j].index
}
return pq[i].freq > pq[j].freq
}
func (pq PQ) Swap(i, j int) {
pq[i], pq[j] = pq[j], pq[i]
}
// Push 往 pq 中放 entry
func (pq *PQ) Push(x interface{}) {
temp := x.(*entry)
*pq = append(*pq, temp)
}
// Pop 从 pq 中取出最优先的 entry
func (pq *PQ) Pop() interface{} {
temp := (*pq)[len(*pq)-1]
*pq = (*pq)[0 : len(*pq)-1]
return temp
}