|
| 1 | +type MedianFinder struct { |
| 2 | + lq Heap |
| 3 | + rq Heap |
| 4 | +} |
| 5 | + |
| 6 | +type Heap []int // S(n) = O(n) |
| 7 | + |
| 8 | +func (pq Heap) Len() int {return len(pq)} |
| 9 | +func (pq Heap) Less(i, j int) bool {return pq[i] < pq[j]} |
| 10 | +func (pq Heap) Swap(i, j int) {pq[i], pq[j] = pq[j], pq[i]} |
| 11 | +func (pq *Heap) Push(x any) {*pq = append(*pq, x.(int))} |
| 12 | +func (pq *Heap) Pop() any { |
| 13 | + x := (*pq)[len(*pq) - 1] |
| 14 | + *pq = (*pq)[: len(*pq) - 1] |
| 15 | + return x |
| 16 | +} |
| 17 | + |
| 18 | + |
| 19 | +func Constructor() MedianFinder { |
| 20 | + return MedianFinder{} |
| 21 | +} |
| 22 | + |
| 23 | + |
| 24 | +func (this *MedianFinder) AddNum(num int) { // T(n) = O(logn) |
| 25 | + if len(this.rq) != 0 && this.rq[0] <= num { |
| 26 | + heap.Push(&this.rq, num) |
| 27 | + if len(this.lq) == len(this.rq) - 1 { |
| 28 | + heap.Push(&this.lq, - heap.Pop(&this.rq).(int)) |
| 29 | + } |
| 30 | + return |
| 31 | + } |
| 32 | + heap.Push(&this.lq, - num) |
| 33 | + if len(this.lq) == len(this.rq) + 2 { |
| 34 | + heap.Push(&this.rq, - heap.Pop(&this.lq).(int)) |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | + |
| 39 | +func (this *MedianFinder) FindMedian() float64 { // T(n) = O(1) |
| 40 | + if len(this.lq) > len(this.rq) { |
| 41 | + return float64(- this.lq[0]) |
| 42 | + } |
| 43 | + return float64(- this.lq[0] + this.rq[0]) / 2 |
| 44 | +} |
| 45 | + |
| 46 | + |
| 47 | +/** |
| 48 | + * Your MedianFinder object will be instantiated and called as such: |
| 49 | + * obj := Constructor(); |
| 50 | + * obj.AddNum(num); |
| 51 | + * param_2 := obj.FindMedian(); |
| 52 | + */ |
0 commit comments