zoukankan      html  css  js  c++  java
  • [LeetCode] Find Median from Data Stream

    Find Median from Data Stream

    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

    Design a data structure that supports the following two operations:

    • void addNum(int num) - Add a integer number from the data stream to the data structure.
    • double findMedian() - Return the median of all elements so far.

    For example:

    add(1)
    add(2)
    findMedian() -> 1.5
    add(3) 
    findMedian() -> 2

     1 class MedianFinder {
     2 private:
     3     multiset<int> left, right;
     4     
     5 public:
     6 
     7     // Adds a number into the data structure.
     8     void addNum(int num) {
     9         if (right.empty() || num < *right.begin()) left.insert(num);
    10         else right.insert(num);
    11     }
    12 
    13     // Returns the median of current data stream
    14     double findMedian() {
    15         int size = left.size() + right.size();
    16         while (left.size() > size / 2) {
    17             int tmp = *left.rbegin();
    18             right.insert(tmp);
    19             left.erase(left.find(tmp));
    20         }
    21         while (left.size() < size / 2) {
    22             int tmp = *right.begin();
    23             left.insert(tmp);
    24             right.erase(right.find(tmp));
    25         }
    26         if (size & 1) return *right.begin();
    27         else return (double)(*left.rbegin() + *right.begin()) / 2;
    28     }
    29 };
    30 
    31 // Your MedianFinder object will be instantiated and called as such:
    32 // MedianFinder mf;
    33 // mf.addNum(1);
    34 // mf.findMedian();
  • 相关阅读:
    3-为什么很多 对 1e9+7(100000007)取模
    6-关于#include<bits/stdc++.h>
    7-n!的位数(斯特灵公式)
    5-math中函数汇总
    6-找数的倍数
    6-Collision-hdu5114(小球碰撞)
    5-青蛙的约会(ex_gcd)
    4-圆数Round Numbers(数位dp)
    4-memset函数总结
    一种Furture模式处理请求中循环独立的任务的方法
  • 原文地址:https://www.cnblogs.com/easonliu/p/4896287.html
Copyright © 2011-2022 走看看