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
    }
}
相关推荐
立志成为coding大牛的菜鸟.31 分钟前
力扣1143-最长公共子序列(Java详细题解)
java·算法·leetcode
鱼跃鹰飞31 分钟前
Leetcode面试经典150题-130.被围绕的区域
java·算法·leetcode·面试·职场和发展·深度优先
GoppViper1 小时前
golang学习笔记29——golang 中如何将 GitHub 最新提交的版本设置为 v1.0.0
笔记·git·后端·学习·golang·github·源代码管理
CV工程师小林8 小时前
【算法】BFS 系列之边权为 1 的最短路问题
数据结构·c++·算法·leetcode·宽度优先
天玑y9 小时前
算法设计与分析(背包问题
c++·经验分享·笔记·学习·算法·leetcode·蓝桥杯
sjsjs119 小时前
【数据结构-一维差分】力扣1893. 检查是否区域内所有整数都被覆盖
数据结构·算法·leetcode
m0_571957589 小时前
Java | Leetcode Java题解之第406题根据身高重建队列
java·leetcode·题解
山脚ice10 小时前
【Hot100】LeetCode—72. 编辑距离
算法·leetcode
鱼跃鹰飞10 小时前
Leetcode面试经典150题-349.两个数组的交集
算法·leetcode·面试
大二转专业12 小时前
408算法题leetcode--第七天
考研·算法·leetcode