Skip to content

Commit 05745f6

Browse files
committed
Update Solution.go
1 parent c563638 commit 05745f6

File tree

1 file changed

+19
-18
lines changed
  • solution/0200-0299/0295.Find Median from Data Stream

1 file changed

+19
-18
lines changed
Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,29 @@
11
type MedianFinder struct {
2-
q1 hp
3-
q2 hp
2+
minq hp
3+
maxq hp
44
}
55

6-
/** initialize your data structure here. */
76
func Constructor() MedianFinder {
87
return MedianFinder{hp{}, hp{}}
98
}
109

1110
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))
1616
}
1717
}
1818

1919
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
2223
}
23-
return float64(this.q1.IntSlice[0]-this.q2.IntSlice[0]) / 2.0
24+
return float64(minq.IntSlice[0])
2425
}
2526

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-
3327
type hp struct{ sort.IntSlice }
3428

3529
func (h hp) Less(i, j int) bool { return h.IntSlice[i] < h.IntSlice[j] }
@@ -39,4 +33,11 @@ func (h *hp) Pop() any {
3933
v := a[len(a)-1]
4034
h.IntSlice = a[:len(a)-1]
4135
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

Comments
 (0)