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
|
type MinHeap struct {
sort.IntSlice
}
func (hp *MinHeap) Less(i, j int) bool {
return hp.IntSlice[i] < hp.IntSlice[j]
}
func (hp *MinHeap) Push(x interface{}) {
hp.IntSlice = append(hp.IntSlice, x.(int))
}
func (hp *MinHeap) Pop() interface{} {
ret := hp.IntSlice[len(hp.IntSlice)-1]
hp.IntSlice = hp.IntSlice[:len(hp.IntSlice)-1]
return ret
}
type MaxHeap struct {
sort.IntSlice
}
func (hp *MaxHeap) Less(i, j int) bool {
return hp.IntSlice[i] > hp.IntSlice[j]
}
func (hp *MaxHeap) Push(x interface{}) {
hp.IntSlice = append(hp.IntSlice, x.(int))
}
func (hp *MaxHeap) Pop() interface{} {
ret := hp.IntSlice[len(hp.IntSlice)-1]
hp.IntSlice = hp.IntSlice[:len(hp.IntSlice)-1]
return ret
}
type MedianFinder struct {
minHeap MinHeap
maxHeap MaxHeap
}
/** initialize your data structure here. */
func Constructor() MedianFinder {
return MedianFinder{minHeap: MinHeap{}, maxHeap: MaxHeap{}}
}
func (this *MedianFinder) AddNum(num int) {
minHeap, maxHeap := &this.minHeap, &this.maxHeap
if len(minHeap.IntSlice) == len(maxHeap.IntSlice) {
if len(maxHeap.IntSlice) == 0 {
heap.Push(maxHeap, num)
} else {
if num > minHeap.IntSlice[0] {
heap.Push(maxHeap, heap.Pop(minHeap))
heap.Push(minHeap, num)
} else {
heap.Push(maxHeap, num)
}
}
} else {
if num > maxHeap.IntSlice[0] {
heap.Push(minHeap, num)
} else {
heap.Push(minHeap, heap.Pop(maxHeap))
heap.Push(maxHeap, num)
}
}
}
func (this *MedianFinder) FindMedian() float64 {
minHeap, maxHeap := &this.minHeap, &this.maxHeap
if len(minHeap.IntSlice) == len(maxHeap.IntSlice) {
return (float64(minHeap.IntSlice[0]) + float64(maxHeap.IntSlice[0])) / 2
} else {
return float64(maxHeap.IntSlice[0])
}
}
/**
* Your MedianFinder object will be instantiated and called as such:
* obj := Constructor();
* obj.AddNum(num);
* param_2 := obj.FindMedian();
*/
|