LINTCODE——数据流中位数

本文介绍了一种在数据流中高效求解中位数的方法。通过使用二分查找法在已排序数组中插入新元素,并保持数组有序,进而快速获取当前数据流的中位数。该方法实现了O(nlogn)的时间复杂度。

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

LINTCODE——数据流中位数

思路:每加入一个新的数,用二分法找到其在数组中的位置,方法O(1)的存储,O(nlogn)的时间

class Solution {
public:
    /*
     * @param nums: A list of integers
     * @return: the median of numbers
     */
    vector<int> medianII(vector<int> &nums) {
        // write your code here
        vector<int> res;

        for(int n = 0 ; n < nums.size() ; n++)
        {

            int L = 0 , R = n-1;
            while(L < R)
            {
                int mid = (L+R)>>1;
                if(nums[n] < nums[mid])
                    R = mid;
                else if(nums[n] > nums[mid])
                    L = mid+1;
                else
                {
                    L = mid;
                    R = mid;
                    break;
                }
            }
            if(nums[n] > nums[L])
            {
                nums.insert(nums.begin()+L+1,nums[n]);

            }
            else
            {
                nums.insert(nums.begin()+L,nums[n]);
            }
            nums.erase(nums.begin()+n+1);


            res.push_back(nums[n/2]);


        }

        return res;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值