C++ solution


  • 0
    G
    class Solution {
    public:
        vector<double> medianSlidingWindow(vector<int>& nums, int k) {
            multiset<int> ms;
            vector<double> result;
            vector<int> num;
            if(nums.size()==0)return result;
            for(int i=0;i<k;i++){
                ms.insert(nums[i]);
                num.push_back(nums[i]);
            }
            multiset<int>::iterator it1, it2;
            it1 = ms.begin();           advance(it1,k/2);
            it2 = ms.begin();           advance(it2,(k-1)/2);
            double res = ((double)(*it1)+(double)(*it2))/2;
            result.push_back(res);
            for(int i=k;i<nums.size();i++){
                ms.insert(nums[i]);
                num.push_back(nums[i]);
                ms.erase(ms.find(nums[i-k]));
                it1 = ms.begin();           advance(it1,k/2);
                it2 = ms.begin();           advance(it2,(k-1)/2);
                double res = ((double)(*it1)+(double)(*it2))/2;
                result.push_back(res);
            }
            return result;
            
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.