[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

思路: 可以维护一个数组, 然后添加的时候使用二分查找,再插入来完成, 时间复杂度为O(n), 因为插入的时候后面的元素要移位. 查询的时候O(1)时间完成.

也尝试过用multiset来做, 其插入时间复杂度是O(log n), 查询时间O(n), 但是过不了.

代码如下:

class MedianFinder {
public:

    // Adds a number into the data structure.
    void addNum(int num) {
        int left = 0, right = nums.size()-1;
        while(left <= right)
        {
            int mid = (left+right)/2;
            if(nums[mid] < num) left = mid+1;
            else right = mid-1;
        }
        nums.insert(nums.begin()+left, num);
    }

    // Returns the median of current data stream
    double findMedian() {
        int n = nums.size();
        if(n%2==1) return nums[n/2];
        return (nums[n/2-1] + nums[n/2])/2.0;
    }
private:
    vector nums;
};

// Your MedianFinder object will be instantiated and called as such:
// MedianFinder mf;
// mf.addNum(1);
// mf.findMedian();

其实上面的做法时间复杂度是不行的,还可以再优化到O(log n).可以选用一个最大堆一个最小堆,保持两个堆的大小平衡,让大顶堆保存小的一半的数,小顶堆保存较大的一半数.

代码如下:

class MedianFinder {
public:

    // Adds a number into the data structure.
    void addNum(int num) {
        small.push(num);
        large.push(-small.top());
        small.pop();
        if(small.size() < large.size())
        {
            small.push(-large.top());
            large.pop();
        }
    }

    // Returns the median of current data stream
    double findMedian() {
        int len = small.size() + large.size();
        if(len%2==1) return small.top();
        return (small.top() - large.top())/2.0;
    }
private:
    priority_queue small, large;
};

// Your MedianFinder object will be instantiated and called as such:
// MedianFinder mf;
// mf.addNum(1);
// mf.findMedian();



你可能感兴趣的:(leetcode,array,优先队列)