📜  使用STL的运行整数流的中位数|套装2

📅  最后修改于: 2021-05-18 00:36:24             🧑  作者: Mango

给定大小为N的数组arr []表示需要作为数据流读取的整数,任务是在读取每个整数后计算并打印中位数。

例子:

方法:可以使用有序集解决问题。请按照以下步骤解决问题:

  • 初始化一个多顺序集,例如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)