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
    }
}
相关推荐
共享家952710 小时前
栈相关算法题解题思路与代码实现分享
c++·leetcode
Wendy_robot10 小时前
【前缀和计算和+哈希表查找次数】Leetcode 560. 和为 K 的子数组
c++·算法·leetcode
o独酌o10 小时前
算法习题-力扣446周赛题解
算法·leetcode
RationalDysaniaer11 小时前
Go设计模式-观察者模式
观察者模式·设计模式·golang
我的golang之路果然有问题11 小时前
案例速成GO+redis 个人笔记
经验分享·redis·笔记·后端·学习·golang·go
云格~11 小时前
Leetcode:1. 两数之和
数据结构·算法·leetcode
xxjiaz12 小时前
水果成篮--LeetCode
java·算法·leetcode·职场和发展
肥or胖12 小时前
【LeetCode 热题 100】链表 系列
算法·leetcode·链表
Y.O.U..12 小时前
力扣HOT100——102.二叉树层序遍历
数据结构·c++·算法·leetcode