[LeetCode 480] Sliding Window Median

本文围绕滑动窗口中位数问题展开,介绍在输入流中求中位数可使用两个size相当的multiset维护,smallSet降序存较小数,bigSet升序存较大数,保证smallSet的size与bigSet的size关系来确定中位数。还提醒删除元素时的注意事项,并给出运行效率。

摘要生成于 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.

Examples: 

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

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

Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Your job is to output the median array for each window in the original array.

For example,
Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.

Window position                Median
---------------               -----
[1  3  -1] -3  5  3  6  7       1
 1 [3  -1  -3] 5  3  6  7       -1
 1  3 [-1  -3  5] 3  6  7       -1
 1  3  -1 [-3  5  3] 6  7       3
 1  3  -1  -3 [5  3  6] 7       5
 1  3  -1  -3  5 [3  6  7]      6

Therefore, return the median sliding window as [1,-1,-1,3,5,6].

Note: 
You may assume k is always valid, ie: k is always smaller than input array's size for non-empty array.

分析

这道题相当于在一个输入流中求中位数。输入流的中位数可以使用两个size相当的multiset来维护,smallSet按照降序排列维护较小的数,bigSet按照升序排列维护较大的数。只要保证smallSet的size与BigSet的size相等或者大1,那么中位数就是smallSet的第一个元素或者smallSet和bigSet的平均值。

这里有一点需要特别注意,multiset在删除元素的时候一定不能用erase函数去删除数字,这样的话会把所有重复的数字全部删除,而应该使用multiset.erase(multiset.find(num))进行删除。我当时在亚马逊面试的时候,就在这一点上犯了很严重的错误。

Code

class Solution {
public:
    vector<double> medianSlidingWindow(vector<int>& nums, int k) {
        vector<double> res;
        int len = nums.size();
        
        for (int i = 0; i < k; i ++)
        {
            insert(nums[i]);
        }
        res.push_back(getMedian());
        for (int i = 1; i <= len -k; i ++)
        {
            remove(nums[i-1]);
            insert(nums[i+k-1]);
            res.push_back(getMedian());
        }
        return res;
    }
    
    void insert(int num)
    {
        if (smallQ.empty() && bigQ.empty())
            smallQ.insert(num);
        else if (!smallQ.empty())
        {
            if (num <= *smallQ.begin())
                smallQ.insert(num);
            else
                bigQ.insert(num);
        }
        else
        {
            if (num >= *bigQ.begin())
                bigQ.insert(num);
            else
                smallQ.insert(num);
        }
        balance();
    }
        
    void remove(int num)
    {
        if (num <= *smallQ.begin())
            smallQ.erase(smallQ.find(num));
        else
            bigQ.erase(bigQ.find(num));
        balance();
    }
    
    void balance()
    {
        while (smallQ.size() < bigQ.size())
        {
            int t = *bigQ.begin();
            bigQ.erase(bigQ.find(t));
            smallQ.insert(t);
        }
        
        while (smallQ.size() > bigQ.size() + 1)
        {
            int t = *smallQ.begin();
            smallQ.erase(smallQ.find(t));
            bigQ.insert(t);
        }
    }
    
    double getMedian()
    {
        if (smallQ.size() == bigQ.size())
            return ((long long)(*smallQ.begin()) + *bigQ.begin())/2.0;
        return *smallQ.begin();
    }

private:
    multiset<int, greater<int>> smallQ;
    multiset<int> bigQ;
    
};

运行效率

Runtime: 92 ms, faster than 30.46% of C++ online submissions for Sliding Window Median.

Memory Usage: 18.1 MB, less than 16.50% of C++ online submissions for Sliding Window Median.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值