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

题目:

题解:

Go 复制代码
type MedianFinder struct {
    nums        *redblacktree.Tree
    total       int
    left, right iterator
}

func Constructor() MedianFinder {
    return MedianFinder{nums: redblacktree.NewWithIntComparator()}
}

func (mf *MedianFinder) AddNum(num int) {
    if count, has := mf.nums.Get(num); has {
        mf.nums.Put(num, count.(int)+1)
    } else {
        mf.nums.Put(num, 1)
    }
    if mf.total == 0 {
        it := mf.nums.Iterator()
        it.Next()
        mf.left = iterator{it, 1}
        mf.right = mf.left
    } else if mf.total%2 == 1 {
        if num < mf.left.Key().(int) {
            mf.left.prev()
        } else {
            mf.right.next()
        }
    } else {
        if mf.left.Key().(int) < num && num < mf.right.Key().(int) {
            mf.left.next()
            mf.right.prev()
        } else if num >= mf.right.Key().(int) {
            mf.left.next()
        } else {
            mf.right.prev()
            mf.left = mf.right
        }
    }
    mf.total++
}

func (mf *MedianFinder) FindMedian() float64 {
    return float64(mf.left.Key().(int)+mf.right.Key().(int)) / 2
}

type iterator struct {
    redblacktree.Iterator
    count int
}

func (it *iterator) prev() {
    if it.count > 1 {
        it.count--
    } else {
        it.Prev()
        it.count = it.Value().(int)
    }
}

func (it *iterator) next() {
    if it.count < it.Value().(int) {
        it.count++
    } else {
        it.Next()
        it.count = 1
    }
}
相关推荐
yaoh.wang2 分钟前
力扣(LeetCode) 69: x 的平方根 - 解法思路
python·算法·leetcode·面试·职场和发展·牛顿法·二分法
YGGP13 分钟前
【Golang】LeetCode 31. 下一个排列
算法·leetcode
元亓亓亓17 分钟前
LeetCode热题100--70. 爬楼梯--简单
算法·leetcode·职场和发展
一起养小猫19 分钟前
LeetCode100天Day3-判断子序列与汇总区间
java·数据结构·算法·leetcode
rannn_11139 分钟前
【SQL题解】力扣高频 SQL 50题|DAY1
后端·sql·题解
黄昏单车40 分钟前
golang语言基础到进阶学习笔记
笔记·golang·go
YGGP40 分钟前
【Golang】LeetCode 75. 颜色分类
算法·leetcode
杜子不疼.1 小时前
【LeetCode 704 & 34_二分查找】二分查找 & 在排序数组中查找元素的第一个和最后一个位置
算法·leetcode·职场和发展
LYFlied1 小时前
【每日算法】LeetCode 437. 路径总和 III
前端·算法·leetcode·面试·职场和发展
alphaTao4 小时前
LeetCode 每日一题 2025/12/15-2025/12/21
算法·leetcode