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
    }
}
相关推荐
超级架构师9 小时前
PRAXO-CORE 2.5.0:用 conformance 和显式边界构建 Go Agent 框架
开发语言·人工智能·后端·golang·ai编程·智能体框架·praxo-core
Tisfy11 小时前
LeetCode 3882.网格图中最小异或路径:动态规划
算法·leetcode·动态规划
A boy CDEF girl12 小时前
算法题专栏:优选算法
数据结构·算法·leetcode
我就是全世界13 小时前
OpenCode Go 套餐划算吗:先看你用哪个模型
开发语言·后端·golang
小杨互联网16 小时前
Go 现代 CLI 工具离线镜像合集
开发语言·后端·golang·开源·go·命令行
驭渊的小故事18 小时前
LeetCode 算法题解:滑动窗口与数组合并的实战应用
算法·leetcode·职场和发展
文丑颜不良啊18 小时前
LeetCode1501~1520题目解析
java·leetcode
microrain19 小时前
跟着一条属性报文走一遍 SagooIoT 的接入链路
物联网·架构·golang·sagooiot
CodeGL19 小时前
微服务框架——go-zero
微服务·架构·golang
Navigator_Z19 小时前
LeetCode //C - 1311. Get Watched Videos by Your Friends
c语言·算法·leetcode