forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.go
42 lines (36 loc) · 998 Bytes
/
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
type MedianFinder struct {
q1 hp
q2 hp
}
/** initialize your data structure here. */
func Constructor() MedianFinder {
return MedianFinder{hp{}, hp{}}
}
func (this *MedianFinder) AddNum(num int) {
heap.Push(&this.q1, num)
heap.Push(&this.q2, -heap.Pop(&this.q1).(int))
if this.q2.Len()-this.q1.Len() > 1 {
heap.Push(&this.q1, -heap.Pop(&this.q2).(int))
}
}
func (this *MedianFinder) FindMedian() float64 {
if this.q2.Len() > this.q1.Len() {
return -float64(this.q2.IntSlice[0])
}
return float64(this.q1.IntSlice[0]-this.q2.IntSlice[0]) / 2.0
}
/**
* Your MedianFinder object will be instantiated and called as such:
* obj := Constructor();
* obj.AddNum(num);
* param_2 := obj.FindMedian();
*/
type hp struct{ sort.IntSlice }
func (h hp) Less(i, j int) bool { return h.IntSlice[i] < h.IntSlice[j] }
func (h *hp) Push(v any) { h.IntSlice = append(h.IntSlice, v.(int)) }
func (h *hp) Pop() any {
a := h.IntSlice
v := a[len(a)-1]
h.IntSlice = a[:len(a)-1]
return v
}