leetcode---Find Median from Data Stream---插入排序

来源:互联网 发布:金轮法王 知乎 编辑:程序博客网 时间:2024/05/02 18:19

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:

addNum(1)
addNum(2)
findMedian() -> 1.5
addNum(3)
findMedian() -> 2

class MedianFinder {public:    /** initialize your data structure here. */    int n;    int arr[100000000];    MedianFinder()     {        n = 0;    }    void addNum(int num)     {        int i = 0;        for(i=0; i<n; i++)        {            if(num < arr[i])                break;        }        for(int j=n-1; j>=i; j--)        {            arr[j+1] = arr[j];        }        arr[i] = num;        n++;        cout << n;    }    double findMedian()     {        if(n & 1)            return arr[n/2];        else            return (arr[(n-1)/2] + arr[n/2])/2.0;    }};/** * Your MedianFinder object will be instantiated and called as such: * MedianFinder obj = new MedianFinder(); * obj.addNum(num); * double param_2 = obj.findMedian(); */
0 0
原创粉丝点击