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.
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] 6Therefore, return the median sliding window as
[1,-1,-1,3,5,6]
.
Note:
You may assume k
is always valid, ie: k
is always smaller than input array's size for non-empty array.
分析
这道题相当于在一个输入流中求中位数。输入流的中位数可以使用两个size相当的multiset来维护,smallSet按照降序排列维护较小的数,bigSet按照升序排列维护较大的数。只要保证smallSet的size与BigSet的size相等或者大1,那么中位数就是smallSet的第一个元素或者smallSet和bigSet的平均值。
这里有一点需要特别注意,multiset在删除元素的时候一定不能用erase函数去删除数字,这样的话会把所有重复的数字全部删除,而应该使用multiset.erase(multiset.find(num))进行删除。我当时在亚马逊面试的时候,就在这一点上犯了很严重的错误。
Code
class Solution {
public:
vector<double> medianSlidingWindow(vector<int>& nums, int k) {
vector<double> res;
int len = nums.size();
for (int i = 0; i < k; i ++)
{
insert(nums[i]);
}
res.push_back(getMedian());
for (int i = 1; i <= len -k; i ++)
{
remove(nums[i-1]);
insert(nums[i+k-1]);
res.push_back(getMedian());
}
return res;
}
void insert(int num)
{
if (smallQ.empty() && bigQ.empty())
smallQ.insert(num);
else if (!smallQ.empty())
{
if (num <= *smallQ.begin())
smallQ.insert(num);
else
bigQ.insert(num);
}
else
{
if (num >= *bigQ.begin())
bigQ.insert(num);
else
smallQ.insert(num);
}
balance();
}
void remove(int num)
{
if (num <= *smallQ.begin())
smallQ.erase(smallQ.find(num));
else
bigQ.erase(bigQ.find(num));
balance();
}
void balance()
{
while (smallQ.size() < bigQ.size())
{
int t = *bigQ.begin();
bigQ.erase(bigQ.find(t));
smallQ.insert(t);
}
while (smallQ.size() > bigQ.size() + 1)
{
int t = *smallQ.begin();
smallQ.erase(smallQ.find(t));
bigQ.insert(t);
}
}
double getMedian()
{
if (smallQ.size() == bigQ.size())
return ((long long)(*smallQ.begin()) + *bigQ.begin())/2.0;
return *smallQ.begin();
}
private:
multiset<int, greater<int>> smallQ;
multiset<int> bigQ;
};
运行效率
Runtime: 92 ms, faster than 30.46% of C++ online submissions for Sliding Window Median.
Memory Usage: 18.1 MB, less than 16.50% of C++ online submissions for Sliding Window Median.