zoukankan      html  css  js  c++  java
  • 支线任务8——寻找中位数

     题目描述

    用以下的一个类实现两个函数

    • 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.
    class MedianFinder {
    public:
    
        // Adds a number into the data structure.
        void addNum(int num) {
            
        }
    
        // Returns the median of current data stream
        double findMedian() {
            
        }
    };
    
    // Your MedianFinder object will be instantiated and called as such:
    // MedianFinder mf;
    // mf.addNum(1);
    // mf.findMedian();

    要实现的功能是能够输出中位数

    由于数据结构刚讲过排序,这个动态的查找中位数让我联想起堆在调整方面的优势。在LeetCode的讨论区内,也是以这种方法为主导(https://leetcode.com/discuss/73981/using-two-heaps-both-big-heap-and-small-heap),我大致试了一下,发现用堆实际速度比较慢。原因可能是有无谓的出队入队浪费了时间。

    尝试了一下,发现用vector直接二分查找插入速度可以提高,其复杂度为 Nlog(N)+N2/4,不失为简单但是高效的算法。代码如下:

    class MedianFinder {
    public:
        // Adds a number into the data structure.
        void addNum(int num) {
            if(!data.size())
            {
                data.push_back(num);
                return;
            }
            int middle;
            int min = 0;
            int max = data.size()-1;
            while(min <= max)
            {
                middle = (min+max)/2;
                if(data[middle] > num)
                    max = middle - 1;
                else 
                    min = middle + 1;
            }
            vector<int>::iterator it = data.begin();
            data.insert(it+min, num);
        }
    
        // Returns the median of current data stream
        double findMedian() {
            return (data[data.size()/2]+data[(data.size()-1)/2])/2.0;
        }
        vector<int>data;
    };

    其实有时候不一定忽视简单常用的数据结构,其受到广泛使用一方面也说明了这种结构的强某些功能的强大

  • 相关阅读:
    Dask教程
    python程序—利用socket监控端口
    python程序—封装案例
    python程序—士兵出击
    Python三大神器:装饰器,迭代器,生成器
    python程序—名片管理系统
    python程序—系统检测
    python程序—用户登录
    (七)javac编译
    Unity系统消息广播
  • 原文地址:https://www.cnblogs.com/zhx14/p/5092618.html
Copyright © 2011-2022 走看看