给定大小为N的数组arr []表示需要作为数据流读取的整数,任务是在读取每个整数后计算并打印中位数。
例子:
Input: arr[] = { 5, 10, 15 }
Output: 5 7.5 10
Explanation:
After reading arr[0] from the data stream, the median is 5.
After reading arr[1] from the data stream, the median is 7.5.
After reading arr[2] from the data stream, the median is 10.
Input: arr[] = { 1, 2, 3, 4 }
Output: 1 1.5 2 2.5
方法:可以使用有序集解决问题。请按照以下步骤解决问题:
- 初始化一个多顺序集,例如mst ,以排序顺序存储数组元素。
- 使用变量i遍历数组。对于每个第i个元素,将arr [i]插入mst并检查变量i是否为偶数。如果发现为真,则使用(* mst.find_by_order(i / 2))打印中位数。
- 否则,通过取(* mst.find_by_order(i / 2))和(* mst.find_by_order((i + 1)/ 2))的平均值来打印中位数。
下面是上述方法的实现:
C++
// C++ program to implement
// the above approach
#include
#include
#include
using namespace __gnu_pbds;
using namespace std;
typedef tree, rb_tree_tag,
tree_order_statistics_node_update> idxmst;
// Function to find the median
// of running integers
void findMedian(int arr[], int N)
{
// Initialise a multi ordered set
// to store the array elements
// in sorted order
idxmst mst;
// Traverse the array
for (int i = 0; i < N; i++) {
// Insert arr[i] into mst
mst.insert(arr[i]);
// If i is an odd number
if (i % 2 != 0) {
// Stores the first middle
// element of mst
double res
= *mst.find_by_order(i / 2);
// Stores the second middle
// element of mst
double res1
= *mst.find_by_order(
(i + 1) / 2);
cout<< (res + res1) / 2.0<<" ";
}
else {
// Stores middle element of mst
double res
= *mst.find_by_order(i / 2);
// Print median
cout << res << " ";
}
}
}
// Driver Code
int main()
{
// Given stream of integers
int arr[] = { 1, 2, 3, 3, 4 };
int N = sizeof(arr) / sizeof(arr[0]);
// Function call
findMedian(arr, N);
}
时间复杂度: O(N * log(N))
辅助空间: O(N)