|
| 1 | +type IntHeap []int |
| 2 | +func (h IntHeap) Len() int { return len(h) } |
| 3 | +func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] } |
| 4 | +func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } |
| 5 | +func (h *IntHeap) Push(x interface{}) {*h = append(*h, x.(int))} |
| 6 | +func (h *IntHeap) Pop() interface{} { |
| 7 | + old := *h |
| 8 | + n := len(old) |
| 9 | + x := old[n-1] |
| 10 | + *h = old[0 : n-1] |
| 11 | + return x |
| 12 | +} |
| 13 | + |
| 14 | +type MedianFinder struct { |
| 15 | + small IntHeap |
| 16 | + large IntHeap |
| 17 | +} |
| 18 | + |
| 19 | + |
| 20 | +func Constructor() MedianFinder { |
| 21 | + return MedianFinder{small: IntHeap{}, large: IntHeap{}} |
| 22 | +} |
| 23 | + |
| 24 | + |
| 25 | +func (this *MedianFinder) AddNum(num int) { |
| 26 | + if len(this.large) > 0 && num > this.large[0] { |
| 27 | + heap.Push(&this.large, num) |
| 28 | + } else { |
| 29 | + heap.Push(&this.small, -1 * num) |
| 30 | + } |
| 31 | + |
| 32 | + if len(this.small) > len(this.large) + 1 { |
| 33 | + val := -1 * heap.Pop(&this.small).(int) |
| 34 | + heap.Push(&this.large, val) |
| 35 | + } |
| 36 | + if len(this.large) > len(this.small) + 1 { |
| 37 | + val := heap.Pop(&this.large).(int) |
| 38 | + heap.Push(&this.small, -1 * val) |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | + |
| 43 | +func (this *MedianFinder) FindMedian() float64 { |
| 44 | + if len(this.small) > len(this.large) { |
| 45 | + return float64(-1 * this.small[0]) |
| 46 | + } else if len(this.large) > len(this.small) { |
| 47 | + return float64(this.large[0]) |
| 48 | + } |
| 49 | + return float64(-1 * this.small[0] + this.large[0]) / 2 |
| 50 | +} |
0 commit comments