码迷,mamicode.com
首页 > 其他好文 > 详细

支线任务8——寻找中位数

时间:2015-12-31 20:59:01      阅读:241      评论:0      收藏:0      [点我收藏+]

标签:

 题目描述

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

  • 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;
};

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

 

支线任务8——寻找中位数

标签:

原文地址:http://www.cnblogs.com/zhx14/p/5092618.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!