【LeetCode】295.寻找数据流中的中位数

295. Find Median from Data Stream

Description:
Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.
Difficulty:hard

Example:

addNum(1)
addNum(2)
findMedian() -> 1.5
addNum(3) 
findMedian() -> 2
方法:最大堆与最小堆
  • Time complexity : O ( l o g n ) O\left ( logn\right ) O(logn)
  • Space complexity : O ( n ) O\left ( n \right ) O(n)
    思路
    首先将数据分为两部分,位于 上边最大堆的数据要比最小堆的数据都要小。
    为了保证将数据平均分配到两个堆中,在动态的操作的过程中两个堆中数据的数目之差不能超过 1
    为了保证 最大堆中的所有数据都小于最小堆中的数据,在操作过程中,新添加进去的数据需要先和最大堆的最大值以及最小堆中的最小值进行比较
    通俗点来讲,我们利用两个堆来存储一个有序数组,最大堆存储元素较小的一半,其堆顶元素有可能参与中位数的计算,最小堆存储元素较大的一半,其堆顶元素有可能参与中位数计算。
#include <vector>
#include <algorithm>
#include <iostream>
#include <queue>
using namespace std;


class MedianFinder {
public:
    /** initialize your data structure here. */
    priority_queue<int, vector<int>> max_heap;
    priority_queue<int, vector<int>, greater<int>> min_heap;
    
    void addNum(int num) {
        max_heap.push(num);
        min_heap.push(max_heap.top());
        max_heap.pop();
        if(max_heap.size() < min_heap.size()){
            max_heap.push(min_heap.top());
            min_heap.pop();
        }
    }
    
    double findMedian() {
        if(max_heap.size() == min_heap.size())
            return (max_heap.top() + min_heap.top()) * 0.5;
        return max_heap.top();
    }
};


int main() {
    MedianFinder a;
    a.addNum(1);
    a.addNum(2);
    cout << a.findMedian() << endl;
    a.addNum(3);
    cout << a.findMedian() << endl;
	a.addNum(4);
    cout << a.findMedian() << endl;
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值