• leetcode@ [295]Find Median from Data Stream


    https://leetcode.com/problems/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     
     3 private: 
     4     priority_queue<int,vector<int>, greater<int> > maxHeap;
     5     priority_queue<int> minHeap;
     6     
     7 public:
     8 
     9     // Adds a number into the data structure.
    10     void addNum(int num) {
    11          if(minHeap.empty() || num <= minHeap.top()){
    12              if(minHeap.size() > maxHeap.size()){
    13                  maxHeap.push(minHeap.top());
    14                  minHeap.pop();
    15              }
    16              minHeap.push(num);
    17          }
    18          else if(maxHeap.empty() || num > maxHeap.top()){
    19              if(maxHeap.size() > minHeap.size()){
    20                  minHeap.push(maxHeap.top());
    21                  maxHeap.pop();
    22              }
    23              maxHeap.push(num);
    24          }
    25          else{
    26              if(maxHeap.size() >= minHeap.size()) minHeap.push(num);
    27              else if(minHeap.size() > maxHeap.size()) maxHeap.push(num);
    28          }
    29     }
    30 
    31     // Returns the median of current data stream
    32     double findMedian() {
    33         if(minHeap.size() == maxHeap.size()) return (double) (minHeap.top() + maxHeap.top()) / 2.0;
    34         else if(minHeap.size() > maxHeap.size()) return (double) minHeap.top();
    35         else return (double) maxHeap.top();
    36     }
    37 };
    38 
    39 // Your MedianFinder object will be instantiated and called as such:
    40 // MedianFinder mf;
    41 // mf.addNum(1);
    42 // mf.findMedian();
  • 相关阅读:
    [转]CR, LF, CR/LF区别与关系
    [转]Maven与nexus关系
    [转]Ubuntu默认使用root用户登录并免去输入密码
    [转]PL/SQL Developer 导入导出csv文件
    [转]关于胖客户端和瘦客户端的理解
    解决win7 安装完jdk7后,再安装jdk8出现的问题 has value '1.8', but '1.7' is required.
    [转]10 Awesome Indicator Applets for Ubuntu’s Unity Desktop
    简单的多对一传输ns2仿真
    论文阅读笔记 (2007-06-09)
    一个简单的ns2实验全过程
  • 原文地址:https://www.cnblogs.com/fu11211129/p/4913848.html
Copyright © 2020-2023  润新知