LeetCode-295 Find Median from Data Stream

博客要求设计一个数据结构,支持插入数字和查找中位数两个操作。解题思路是每次插入时用二分查找确定位置以保持数字有序,查找中位数时输出中间数字。时间复杂度为O(N*log(N)),空间复杂度为O(N)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

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.

For example,

[2,3,4], the median is 3

[2,3], the median is (2 + 3) / 2 = 2.5

Design a data structure that supports the following two operations:

  • void addNum(int num) - Add a integer number from the data stream to the data structure.
  • double findMedian() - Return the median of all elements so far.

 

题目大意

要求完成两个操作:插入数字,找到插入数字的中位数(若插入了偶数个数字,则中位数为中间两个数字的平均值)。

 

示例

E1

addNum(1)
addNum(2)
findMedian() -> 1.5
addNum(3) 
findMedian() -> 2

 

解题思路

在每次插入的时候二分查找到应该插入的位置,使得所有数字保持有序。最后查找中位数的时候只需要输出中间的数字即可。

 

复杂度分析

时间复杂度:O(N*log(N))

空间复杂度:O(N)

 

代码

class MedianFinder {
public:
    /** initialize your data structure here. */
    MedianFinder() {
        
    }
    
    void addNum(int num) {
        if(nums.empty())
            nums.push_back(num);
        else {
            // 插入数字,使得所有数字有序排列
            nums.insert(lower_bound(nums.begin(), nums.end(), num), num);
        }
    }
    
    double findMedian() {
        int n = nums.size();
        // 访问中间的位置,需判断数字总数是否为偶数
        return n & 1 ? nums[n / 2] : (nums[n / 2 - 1] + nums[n / 2]) * 0.5;
    }
    
private:
    vector<int> nums;
};

/**
 * Your MedianFinder object will be instantiated and called as such:
 * MedianFinder* obj = new MedianFinder();
 * obj->addNum(num);
 * double param_2 = obj->findMedian();
 */

 

转载于:https://www.cnblogs.com/heyn1/p/11155965.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值