back_space

导航

 

 题目描述

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

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

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

 

posted on 2015-12-31 20:34  back_space  阅读(258)  评论(0编辑  收藏  举报