LeetCode-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.

 

简而言之,就是实现一个数据结构,可以实现插入操作,并且得到一组数的中位数。

 

二.首先,因为这是一组数,容易想到用vector储存。因为要找到一组数的中位数需要先排好序,所以想到在插入时同时进行排序。为了优化算法的性能,我们可以使用二分法插入,边插入边排序。这样做的好处是时刻保持这组数是一个排好序的状态,在求中位数操作时时间复杂度为O(1)。

因为这道题比较简单,主要就是利用了二分法的思想,所以直接贴出了代码如下:

class MedianFinder {
public:
    
    vector<int> nums;
    // Adds a number into the data structure.
    void addNum(int num) {
        if(!nums.size())
        {  
            nums.push_back(num);
            return;
        }
        int start = 0; 
        int end = nums.size() - 1;
        int mid = (start + end) / 2;
        while(1)
        {
            mid = (start + end) / 2;
            if(num == nums[mid])
            {
                nums.insert(nums.begin() + mid, num);
                break;
            }
            else if(num > nums[mid])
            {
                start = mid + 1;
            }
            else
            {
                end = mid - 1;
            }
            if(start > end)
            {
                nums.insert(nums.begin() + start, num);
                break;
            }
        }
        return;
    }

    // Returns the median of current data stream
    double findMedian() {
        if(nums.size() % 2)
            return nums[nums.size() / 2];
        else
            return ((double)nums[nums.size() / 2] + (double)nums[nums.size() / 2 - 1]) / 2;
    }
};

发现自己永远想不起来int到double的强制类型转换...不过好在这个错误还比较容易看出来...

 

三.总结

看了其他同学的博客发现还可以使用各种自带排序功能的STL结构,然而我却想不到T_T

只能想到傻傻的vector,真是心塞...

posted @ 2015-12-30 17:38  铁之贝克  阅读(195)  评论(0编辑  收藏  举报