Sliding Window Median

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 values.

Examples:

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

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

Given an array num, 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].

Example:

Input:  nums[]={1,3,-1,-3,5,3,6,7}, k= 3
Output: [1,-1,-1,3,5,6]

Approach

C++

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

multiset<doublest;
double median()
{
    double a = *next(st.begin(), st.size() / 2 - 1);
    double b = *next(st.begin(), st.size() / 2);
    if (st.size() & 1)
        return b;
    return (a + b) / 2;
}
vector<doublemedianSlidingWindow(vector<int&numsint k)
{
    st.clear();
    vector<doubleres;
    for (int i = 0i < ki++)
        st.insert(nums[i]);
    for (int i = ki < nums.size(); i++)
    {
        res.push_back(median());
        st.erase(st.find(nums[i - k]));
        st.insert(nums[i]);
    }
    res.push_back(median());
    return res;
}
int main()
{
    vector<intnums = {13, -1, -35367};
    int k = 3;

    vector<doublemedian = medianSlidingWindow(numsk);

    cout << "[";
    for (int i = 0i < median.size(); i++)
    {
        cout << median[i];
        if (i != median.size() - 1)
            cout << ",";
    }
    cout << "]";
}


No comments:

Post a Comment