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
    }
}
相关推荐
小辉同志2 小时前
78. 子集
算法·leetcode·深度优先
白毛大侠3 小时前
Go Goroutine 与用户态是进程级
开发语言·后端·golang
Demon--hx5 小时前
[LeetCode]100 链表-专题
算法·leetcode·链表
_深海凉_5 小时前
LeetCode热题100-LRU 缓存
算法·leetcode·缓存
lolo大魔王6 小时前
Go语言的基础语法
开发语言·后端·golang
liuyao_xianhui6 小时前
优选算法_岛屿的最大面积_floodfill算法_C++
java·开发语言·数据结构·c++·算法·leetcode·链表
We་ct7 小时前
LeetCode 190. 颠倒二进制位:两种解法详解
前端·算法·leetcode·typescript
禹中一只鱼7 小时前
【力扣热题100学习笔记】 - 双指针
java·笔记·学习·leetcode·贪心算法
cpp_25017 小时前
P1569 [USACO ?] Generic Cow Protests【来源请求】
数据结构·c++·算法·题解·洛谷·线性dp