求变化序列的中位数
一、数据流(LC 295)
1.题目
The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value and the median is the mean of the two middle values.
For example, for arr = [2,3,4], the median is 3.
For example, for arr = [2,3], the median is (2 + 3) / 2 = 2.5.
Implement the MedianFinder class:
MedianFinder() initializes the MedianFinder object.
void addNum(int num) adds the integer num from the data stream to the data structure.
double findMedian() returns the median of all elements so far. Answers within 10-5 of the actual answer will be accepted.
2.思路
用大根堆和小根堆维护较大的一堆元素和较小的一堆元素。
3.代码
class MedianFinder {
public:
priority_queue<int> bottom;
priority_queue<int, vector<int>, greater<int>> tt;
int count;
/** initialize your data structure here. */
MedianFinder() {
count = 0;
}
void addNum(int num) {
if (!count || num < bottom.top()) {
bottom.push(num);
if (bottom.size() > tt.size() + 1) {
tt.push(bottom.top());
bottom.pop();
}
}
else {
tt.push(num);
if (tt.size() >= bottom.size() + 1) {
bottom.push(tt.top());
tt.pop();
}
}
count++;
}
double findMedian() {
if (count % 2 == 0) return ((double)tt.top() + bottom.top()) / 2;
else return bottom.top();
}
};
二、滑动窗口(LC 480)
1.题目
求滑动窗口中位数
2.思路
用大根堆和小根堆维护较大的一堆元素和较小的一堆元素,但是这里需要移除窗口外的元素,用priority queue做不了,因此用multiset(有序,方便移除指定元素)模拟大根堆和小根堆。
3.代码
class Solution {
public:
multiset<int> left, right;
int k;
double getmedium() {
if (k % 2 != 0) {
return *right.begin();
}
else {
return ((double)*right.begin() + *left.rbegin()) / 2;
}
}
vector<double> medianSlidingWindow(vector<int>& nums, int _k) {
k = _k;
vector<double> res;
for (int i = 0; i < k; i++) right.insert(nums[i]);
for (int i = 0; i < k / 2; i++) {
left.insert(*right.begin());
right.erase(right.begin());
}
res.push_back(getmedium());
for (int i = k; i < nums.size(); i++) {
int x = nums[i], y = nums[i - k];
if (x >= *right.begin()) right.insert(x);
else left.insert(x);
if (y >= *right.begin()) right.erase(right.find(y));
else left.erase(left.find(y));
//更新两个堆,使两边个数相差不超过1
while (left.size() > right.size()) {
right.insert(*left.rbegin());
left.erase(left.find(*left.rbegin()));
}
while (right.size() > left.size() + 1) {
left.insert(*right.begin());
right.erase(right.begin());
}
res.push_back(getmedium());
}
return res;
}
};