Sliding Window Median

LeetCode #480


Description:

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.

Example:

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: 1 ≤ k ≤ input array's size for non-empty array.

Idea:

multiset是个bst,默认ascending。用multiset,取中间值就行。对于multiset,如果插入值于某个element相同,则插在右边。

为了速度,不要每次都取中间值,而是保持一个mid iterator,每次插入和删除的时候看要不要移动mid。

我用笨办法,用leftsize和rightsize两个变量来看mid左边和右边的size。

Time: O(n logk)

Code:

class Solution {
public:
    vector<double> medianSlidingWindow(vector<int>& nums, int k) {

        multiset<int> bst_set(nums.begin(), nums.begin()+k);
        auto it=next(bst_set.begin(), k/2);
        bool flag_even = k%2==0;
        int left_size= flag_even? k/2: k/2;
        int right_size= flag_even? k/2-1: k/2;

        vector<double> result;
        double median_loc = flag_even? (*it * 1.0 + *prev(it))/2.0 : *it;
        result.push_back(median_loc);

        for(int i=k; i<nums.size(); i++){
            bst_set.insert(nums[i]);
            if(nums[i]>=*it) right_size++;
            else left_size++;

            if(nums[i-k]<*it) left_size--;
            else if(nums[i-k]>*it) right_size--;
            else{
                it++;
                right_size--;
            }

            bst_set.erase(bst_set.lower_bound(nums[i-k]));

            if(right_size>left_size){
                it++;
                left_size++;
                right_size--;
            }
            else if(left_size > right_size + 1){
                it--;
                left_size--;
                right_size++;
            }

            median_loc = flag_even? (*it * 1.0 + *prev(it))/2.0 : *it;
            result.push_back(median_loc);
        }

        return result;
    }
};

results matching ""

    No results matching ""