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

    xiaoxiao2021-03-25  97

    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(); */
    转载请注明原文地址: https://ju.6miu.com/read-26307.html

    最新回复(0)