力扣295. 数据流的中位数

Problem: 295. 数据流的中位数

题目描述

在这里插入图片描述在这里插入图片描述

思路

1.定义一个大顶堆和小顶堆;
2.当添加的数据小于大顶堆的堆顶元素或者大顶堆为空时,将元素添加到大顶堆;当元素大于大顶堆堆顶元素时添加到小顶堆;同时维护大小顶堆,当大顶堆的元素个数小于小顶堆时,将小顶堆多出大顶堆个数的堆顶元素拿出添加到大顶堆;当小顶堆元素小于大顶堆元素个数减1时将大顶堆多出的堆顶元素添加到小顶堆;
3.当大小顶堆的元素个数一样时,取各自的堆顶元素相加除以2;否则取出大顶堆的堆顶元素;

复杂度

时间复杂度:

O ( l o g n ) O(logn) O(logn);其中 n n n为数据数据流的数据个数

空间复杂度:

O ( n ) O(n) O(n)

Code

class MedianFinder {
private:
    // Maintain a max heap and a min heap
    priority_queue<int, vector<int>, less<int>> maxHeap;
    priority_queue<int, vector<int>, greater<int>> minHeap;

public:
    // Constructor
    MedianFinder() {

    }

    // Insert data into the data stream
    void addNum(int num) {
        if (maxHeap.empty() || num <= maxHeap.top()) {
            maxHeap.push(num);
        } else {
            minHeap.push(num);
        }

        // Maintain the number relationship between two heaps
        // 1. The number of elements in the max heap is not less than that in the min heap
        // 2. The number of min heap elements can be less than the number of max heap elements minus 1
        while (maxHeap.size() < minHeap.size()) {
            int temp = minHeap.top();
            minHeap.pop();
            maxHeap.push(temp);
        }

        while (minHeap.size() < maxHeap.size() - 1) {
            int temp = maxHeap.top();
            maxHeap.pop();
            minHeap.push(temp);
        }
    }

    // Find the median
    double findMedian() {
        if (maxHeap.size() == minHeap.size()) {
            return (minHeap.top() + maxHeap.top()) / 2.0;
        } else {
            return maxHeap.top();
        }
    }
};
  • 15
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值