题目:数据流中位数
要求:
数字是不断进入数组的,在每次添加一个新的数进入数组的同时返回当前新数组的中位数。
说明
中位数的定义:
中位数是排序后数组的中间值,如果有数组中有n个数,则中位数为A[(n-1)/2]。
比如:数组A=[1,2,3]的中位数是2,数组A=[1,19]的中位数是1。
样例:
持续进入数组的数的列表为:[1, 2, 3, 4, 5],则返回[1, 1, 2, 2, 3]
持续进入数组的数的列表为:[4, 5, 1, 3, 2, 6, 0],则返回 [4, 4, 4, 3, 3, 3, 3]
持续进入数组的数的列表为:[2, 20, 100],则返回[2, 2, 20]
算法要求:
时间复杂度为O(nlogn)
解题思路:
首先,我们使用Multiset插入数字,插入的时间复杂度为logN,接着使用迭代器,刚开始指向第一个,根据插入的情况来移动指针即可,移动指针带来的复杂度为2n,即O(n(logn + 2)),省略得O(nlogn)
算法如下:
class Solution {
public:
/**
* @param nums: A list of integers.
* @return: The median of numbers
*/
vector<int> medianII(vector<int> &nums) {
// write your code here
vector<int> vec;
multiset<int> temp;
int size = nums.size();
if (size == 0) {
return vec;
}
temp.insert(nums[0]);
multiset<int>::iterator it = temp.begin();
vec.push_back(*it);
for (int i = 1; i < size; i++) {
temp.insert(nums[i]);
if (nums[i] < *it) {
it--;
}
if (i % 2 == 0) {
it++;
}
vec.push_back(*it);
}
return vec;
}
};