1
1
type MedianFinder struct {
2
- q1 hp
3
- q2 hp
2
+ minq hp
3
+ maxq hp
4
4
}
5
5
6
- /** initialize your data structure here. */
7
6
func Constructor () MedianFinder {
8
7
return MedianFinder {hp {}, hp {}}
9
8
}
10
9
11
10
func (this * MedianFinder ) AddNum (num int ) {
12
- heap .Push (& this .q1 , num )
13
- heap .Push (& this .q2 , - heap .Pop (& this .q1 ).(int ))
14
- if this .q2 .Len ()- this .q1 .Len () > 1 {
15
- heap .Push (& this .q1 , - heap .Pop (& this .q2 ).(int ))
11
+ minq , maxq := & this .minq , & this .maxq
12
+ heap .Push (maxq , - num )
13
+ heap .Push (minq , - heap .Pop (maxq ).(int ))
14
+ if minq .Len ()- maxq .Len () > 1 {
15
+ heap .Push (maxq , - heap .Pop (minq ).(int ))
16
16
}
17
17
}
18
18
19
19
func (this * MedianFinder ) FindMedian () float64 {
20
- if this .q2 .Len () > this .q1 .Len () {
21
- return - float64 (this .q2 .IntSlice [0 ])
20
+ minq , maxq := this .minq , this .maxq
21
+ if minq .Len () == maxq .Len () {
22
+ return float64 (minq .IntSlice [0 ]- maxq .IntSlice [0 ]) / 2
22
23
}
23
- return float64 (this . q1 . IntSlice [0 ]- this . q2 . IntSlice [ 0 ]) / 2.0
24
+ return float64 (minq . IntSlice [0 ])
24
25
}
25
26
26
- /**
27
- * Your MedianFinder object will be instantiated and called as such:
28
- * obj := Constructor();
29
- * obj.AddNum(num);
30
- * param_2 := obj.FindMedian();
31
- */
32
-
33
27
type hp struct { sort.IntSlice }
34
28
35
29
func (h hp ) Less (i , j int ) bool { return h .IntSlice [i ] < h .IntSlice [j ] }
@@ -39,4 +33,11 @@ func (h *hp) Pop() any {
39
33
v := a [len (a )- 1 ]
40
34
h .IntSlice = a [:len (a )- 1 ]
41
35
return v
42
- }
36
+ }
37
+
38
+ /**
39
+ * Your MedianFinder object will be instantiated and called as such:
40
+ * obj := Constructor();
41
+ * obj.AddNum(num);
42
+ * param_2 := obj.FindMedian();
43
+ */
0 commit comments