Sliding Window Median

Description:

Given an array of n integer, and a moving window(size k), move the window at each iteration from the start of the array, find the median of the element inside the window at each moving. (If there are even numbers in the array, return the N/2-th number after sorting the element in the window. )

Example

For array [1,2,7,8,5], moving window size k = 3. return [2,7,7]

At first the window is at the start of the array like this

[ | 1,2,7 | ,8,5] , return the median 2;

then the window move one step forward.

[1, | 2,7,8 | ,5], return the median 7;

then the window move one step forward again.

[1,2, | 7,8,5 | ], return the median 7;

Challenge

Total run time in O(nlogn).

Solution:

class Solution {
public:
	/**
	 * @param nums: A list of integers.
	 * @return: The median of the element inside the window at each moving
	 */
	vector<int> medianSlidingWindow(vector<int> &nums, int k) {
		vector<int> rc;
		auto sz = (int)nums.size();
		if (sz == 0 || sz < k) return rc;
		multiset<int> left, right;
		for (int i = 0; i < k; ++i) {
			if (left.size() < (k-1)/2+1) left.insert(nums[i]);
			else if (nums[i] >= *left.rbegin()) right.insert(nums[i]);
			else {
				right.insert(*left.rbegin());
				left.erase(prev(end(left)));
				left.insert(nums[i]);
			}
		}
		rc.push_back(*left.rbegin());
		for (int i = k; i < sz; ++i) {
			if (nums[i-k] <= *left.rbegin()) {
				left.erase(left.find(nums[i-k]));
				if (!right.empty() && nums[i] > *right.begin()) {
					left.insert(*right.begin());
					right.erase(right.begin());
					right.insert(nums[i]);
				} else
					left.insert(nums[i]);
			} else {
				right.erase(right.find(nums[i-k]));
				if (nums[i] < *left.rbegin()) {
					right.insert(*left.rbegin());
					left.erase(prev(end(left)));
					left.insert(nums[i]);
				} else
					right.insert(nums[i]);
			}
			rc.push_back(*left.rbegin());
		}
		return rc;
	}
};
posted @ 2015-10-10 16:25  影湛  阅读(177)  评论(0编辑  收藏  举报