Sliding Median

You are given an array of n integers. Your task is to calculate the median of each window of k elements, from left to right.

The median is the middle element when the elements are sorted. If the number of elements is even, there are two possible medians and we assume that the median is the smaller of them.

Example:

Input: n = 8, k = 3, arr = {2, 4, 3, 5, 8, 1, 2, 1}
Output: 3 4 5 5 2 1 

Approach

C++

#include <bits/stdc++.h>
using namespace std;

#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
template <class T>
using ordered_set = tree<Tnull_typeless<T>,
                         rb_tree_tag,
                         tree_order_statistics_node_update>;

void slidingMedian(int nint kvector<int&arr)
{

    ordered_set<array<int2>> orderSet;
    for (int i = 0i < ki++)
        orderSet.insert({arr[i]i});
    int med = (*orderSet.find_by_order((k - 1) / 2))[0];
    cout << med << " ";
    for (int i = 0j = kj < ni++, j++)
    {
        orderSet.erase({arr[i]i});
        orderSet.insert({arr[j]j});
        med = (*orderSet.find_by_order((k - 1) / 2))[0];
        cout << med << " ";
    }
    cout << "\n";
}

int main()
{

    int n = 8k = 3;
    vector<intarr = {24358121};

    slidingMedian(nkarr);

    return 0;
}


No comments:

Post a Comment