295.find-median-from-data-stream.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import (
  2. "container/heap"
  3. )
  4. type MedianFinder struct {
  5. max MaxHeap // The left part (smaller part) of data
  6. min MinHeap // The right part of data
  7. odd bool
  8. }
  9. /** initialize your data structure here. */
  10. func Constructor() (mf MedianFinder) {
  11. return
  12. }
  13. func (this *MedianFinder) AddNum(num int) {
  14. if this.max.length == 0 || num < this.max.Max() {
  15. heap.Push(&this.max, num)
  16. if this.max.length-this.min.length == 2 {
  17. heap.Push(&this.min, heap.Pop(&this.max))
  18. }
  19. } else {
  20. heap.Push(&this.min, num)
  21. if this.min.length-this.max.length == 1 {
  22. heap.Push(&this.max, heap.Pop(&this.min))
  23. }
  24. }
  25. this.odd = !this.odd
  26. }
  27. func (this *MedianFinder) FindMedian() float64 {
  28. if this.odd {
  29. return float64(this.max.Max())
  30. }
  31. return float64(this.max.Max()+this.min.Min()) / 2.0
  32. }
  33. type MaxHeap struct {
  34. heap []int
  35. length int
  36. }
  37. func (max MaxHeap) Len() int { return max.length }
  38. func (max MaxHeap) Less(i, j int) bool { return max.heap[i] > max.heap[j] }
  39. func (max MaxHeap) Swap(i, j int) { max.heap[i], max.heap[j] = max.heap[j], max.heap[i] }
  40. func (max MaxHeap) Max() int {
  41. return max.heap[0]
  42. }
  43. func (max *MaxHeap) Push(x interface{}) {
  44. max.heap = append(max.heap, x.(int))
  45. max.length++
  46. }
  47. func (max *MaxHeap) Pop() interface{} {
  48. max.length--
  49. top := max.heap[max.length]
  50. max.heap = max.heap[:max.length]
  51. return top
  52. }
  53. type MinHeap struct {
  54. heap []int
  55. length int
  56. }
  57. func (min MinHeap) Len() int { return min.length }
  58. func (min MinHeap) Less(i, j int) bool { return min.heap[i] < min.heap[j] }
  59. func (min MinHeap) Swap(i, j int) { min.heap[i], min.heap[j] = min.heap[j], min.heap[i] }
  60. func (min MinHeap) Min() int {
  61. return min.heap[0]
  62. }
  63. func (min *MinHeap) Push(x interface{}) {
  64. min.heap = append(min.heap, x.(int))
  65. min.length++
  66. }
  67. func (min *MinHeap) Pop() interface{} {
  68. min.length--
  69. top := min.heap[min.length]
  70. min.heap = min.heap[:min.length]
  71. return top
  72. }
  73. /**
  74. * Your MedianFinder object will be instantiated and called as such:
  75. * obj := Constructor();
  76. * obj.AddNum(num);
  77. * param_2 := obj.FindMedian();
  78. */