秋招力扣刷题——数据流的中位数

一、题目要求

中位数是有序整数列表中的中间值。如果列表的大小是偶数,则没有中间值,中位数是两个中间值的平均值。

例如 arr = [2,3,4] 的中位数是 3 。

例如 arr = [2,3] 的中位数是 (2 + 3) / 2 = 2.5 。

实现 MedianFinder 类:

MedianFinder() 初始化 MedianFinder 对象。

void addNum(int num) 将数据流中的整数 num 添加到数据结构中。

double findMedian() 返回到目前为止所有元素的中位数。与实际答案相差 10-5 以内的答案将被接受。

示例 1:

输入

"MedianFinder", "addNum", "addNum", "findMedian", "addNum", "findMedian"

\[\], \[1\], \[2\], \[\], \[3\], \[\]

输出

null, null, null, 1.5, null, 2.0

解释

MedianFinder medianFinder = new MedianFinder();

medianFinder.addNum(1); // arr = [1]

medianFinder.addNum(2); // arr = [1, 2]

medianFinder.findMedian(); // 返回 1.5 ((1 + 2) / 2)

medianFinder.addNum(3); // arr[1, 2, 3]

medianFinder.findMedian(); // return 2.0

提示:

-105 <= num <= 105

在调用 findMedian 之前,数据结构中至少有一个元素

最多 5 * 104 次调用 addNum 和 findMedian

二、实现代码

原理 :使用了两个堆存储数据,一个最大堆用于存储较小的一半元素,另一个最小堆用于存储较大的一半元素,然后根据堆顶元素计算得到中位数。
1. Java

bash 复制代码
class MedianFinder {
    private PriorityQueue<Integer> low;
    private PriorityQueue<Integer> high;

    public MedianFinder() {
        // Max-heap to store the smaller half elements
        low = new PriorityQueue<>((a, b) -> b - a);
        // Min-heap to store the larger half elements
        high = new PriorityQueue<>();
    }

    public void addNum(int num) {
        low.offer(num);
        high.offer(low.poll());
        if (low.size() < high.size()) {
            low.offer(high.poll());
        }
    }

    public double findMedian() {
        if (low.size() > high.size()) {
            return low.peek();
        } else {
            return (low.peek() + high.peek()) / 2.0;
        }
    }
}

2. C++

bash 复制代码
class MedianFinder {
private:
    priority_queue<int> low; // Max-heap
    priority_queue<int, vector<int>, greater<int>> high; // Min-heap

public:
    MedianFinder() { }

    void addNum(int num) {
        low.push(num);
        high.push(low.top());
        low.pop();
        if (low.size() < high.size()) {
            low.push(high.top());
            high.pop();
        }
    }

    double findMedian() {
        if (low.size() > high.size()) {
            return low.top();
        } else {
            return (low.top() + high.top()) / 2.0;
        }
    }
};

3. Python3

bash 复制代码
class MedianFinder:

    def __init__(self):
        self.low = []  # max-heap (inverted min-heap)
        self.high = []  # min-heap

    def addNum(self, num: int) -> None:
        heapq.heappush(self.low, -num)
        heapq.heappush(self.high, -heapq.heappop(self.low))
        if len(self.low) < len(self.high):
            heapq.heappush(self.low, -heapq.heappop(self.high))

    def findMedian(self) -> float:
        if len(self.low) > len(self.high):
            return -self.low[0]
        else:
            return (-self.low[0] + self.high[0]) / 2.0

:如果四python会出错,只能是python3

相关推荐
烁3472 分钟前
每日一题(小白)动态规划篇2
算法·动态规划
风象南2 分钟前
Spring Boot 实现文件秒传功能
java·spring boot·后端
橘猫云计算机设计3 分钟前
基于django优秀少儿图书推荐网(源码+lw+部署文档+讲解),源码可白嫖!
java·spring boot·后端·python·小程序·django·毕业设计
黑猫Teng6 分钟前
Spring Boot拦截器(Interceptor)与过滤器(Filter)深度解析:区别、实现与实战指南
java·spring boot·后端
互联网杂货铺9 分钟前
如何用Postman实现自动化测试?
自动化测试·软件测试·python·测试工具·测试用例·接口测试·postman
星河浪人12 分钟前
Spring Boot启动流程及源码实现深度解析
java·spring boot·后端
佩奇的技术笔记13 分钟前
中级:Maven面试题精讲
java·面试·maven
予安灵16 分钟前
一文详细讲解Python(详细版一篇学会Python基础和网络安全)
开发语言·python
Lizhihao_24 分钟前
JAVA-堆 和 堆排序
java·开发语言
极客先躯29 分钟前
高级java每日一道面试题-2025年3月21日-微服务篇[Nacos篇]-什么是Nacos?
java·开发语言·微服务