当前位置:   article > 正文

Golang | Leetcode Golang题解之第295题数据流的中位数

Golang | Leetcode Golang题解之第295题数据流的中位数

题目:

题解:

  1. type MedianFinder struct {
  2. nums *redblacktree.Tree
  3. total int
  4. left, right iterator
  5. }
  6. func Constructor() MedianFinder {
  7. return MedianFinder{nums: redblacktree.NewWithIntComparator()}
  8. }
  9. func (mf *MedianFinder) AddNum(num int) {
  10. if count, has := mf.nums.Get(num); has {
  11. mf.nums.Put(num, count.(int)+1)
  12. } else {
  13. mf.nums.Put(num, 1)
  14. }
  15. if mf.total == 0 {
  16. it := mf.nums.Iterator()
  17. it.Next()
  18. mf.left = iterator{it, 1}
  19. mf.right = mf.left
  20. } else if mf.total%2 == 1 {
  21. if num < mf.left.Key().(int) {
  22. mf.left.prev()
  23. } else {
  24. mf.right.next()
  25. }
  26. } else {
  27. if mf.left.Key().(int) < num && num < mf.right.Key().(int) {
  28. mf.left.next()
  29. mf.right.prev()
  30. } else if num >= mf.right.Key().(int) {
  31. mf.left.next()
  32. } else {
  33. mf.right.prev()
  34. mf.left = mf.right
  35. }
  36. }
  37. mf.total++
  38. }
  39. func (mf *MedianFinder) FindMedian() float64 {
  40. return float64(mf.left.Key().(int)+mf.right.Key().(int)) / 2
  41. }
  42. type iterator struct {
  43. redblacktree.Iterator
  44. count int
  45. }
  46. func (it *iterator) prev() {
  47. if it.count > 1 {
  48. it.count--
  49. } else {
  50. it.Prev()
  51. it.count = it.Value().(int)
  52. }
  53. }
  54. func (it *iterator) next() {
  55. if it.count < it.Value().(int) {
  56. it.count++
  57. } else {
  58. it.Next()
  59. it.count = 1
  60. }
  61. }
声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号