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
    }
}
相关推荐
失去的青春---夕阳下的奔跑7 小时前
560. 和为 K 的子数组
数据结构·算法·leetcode
m0_629494738 小时前
LeetCode 热题 100-----25.回文链表
数据结构·算法·leetcode·链表
吃着火锅x唱着歌10 小时前
LeetCode 1019.链表中的下一个更大节点
算法·leetcode·链表
凌波粒11 小时前
LeetCode--404.左叶子之和(二叉树)
算法·leetcode·职场和发展
绝知此事11 小时前
【算法突围 03】核心算法思想:分治/递归/动态规划与 LeetCode 高频真题解析
算法·leetcode·面试·动态规划
宇明一不急11 小时前
go 链表 (标准库实现)
开发语言·链表·golang
阿Y加油吧13 小时前
两道字符串 DP 模板题复盘:最长公共子序列 & 编辑距离
leetcode
~|Bernard|13 小时前
GO语言中哪些类型是可比较类型的(==和!=)
开发语言·后端·golang
我爱cope13 小时前
【力扣hot100:76. 最小覆盖子串】
算法·leetcode·职场和发展
sheeta199813 小时前
LeetCode 每日一题笔记 日期:2026.05.20 题目:2657. 找到前缀公共数组
笔记·算法·leetcode