面试题41:数据中的中位数

如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。我们使用Insert()方法读取数据流,使用GetMedian()方法获取当前读取数据的中位数。

下次一定记住不要再用cout,cin。。。。。。

解题思路

  • 插入到没排序的数组

  • 插入到排序的数组

  • 插入到排序的链表

  • 插入到二叉搜索树

  • 插入到平衡树(比较难实现,比如红黑树)

  • 插入到堆(效率最高O(logn)、O(1),比较难实现)

上代码(C++香)

插入并排序O(logn),查找中位数O(1)
#include <iostream>
#include <algorithm>
#include <math.h>
#include <cstring>
#include "ListNode.h"
#include "TreeNode.h"
#include "Graph.h"
using namespace std;

#define MAXNUM 100010
#define DRIFT 1001

vector<int> numbers;

void mySwap(vector<int> &num, int i, int j){
    int temp = num[j];
    num[j] = num[i];
    num[i] = temp;
}

int myPartition(vector<int> &num, int low, int high){
    int pivot = num[low];
    while(low < high){
        // 将右边比pivot小的放到左边
        while(low < high && num[high] >= pivot)
            high--;
        mySwap(num, low, high);
        while(low < high && num[low] <= pivot)
            low++;
        mySwap(num, low, high);
    }
    return low;
}

// 快排
void QSort(vector<int> &num, int low, int high){
    if(low >= high)
        return ;
    int pivot = myPartition(num, low, high);
    QSort(num, low, pivot - 1);
    QSort(num, pivot + 1, high);
}

// 插入到排序的数组中
void Insert(int num){
    numbers.push_back(num);
    QSort(numbers, 0, numbers.size() - 1);
}

// 获取中位数
double GetMedian(){
    int length = numbers.size();
    if(length == 0)
        return 0.0;

    double ans = 0.0;
    // 奇数
    if(length % 2)
        ans = (double)numbers[length/2];
    // 偶数
    else
        ans = (double)numbers[length/2-1] + ((double)(numbers[length/2] - numbers[length/2-1])) / 2;

    return ans;
}

int main()
{
    Insert(1);
    Insert(2);
    Insert(3);
    Insert(4);
    Insert(5);
    Insert(6);
    cout<<GetMedian();
    return 0;
}

posted @ 2020-08-18 21:28  程序员曾奈斯  阅读(236)  评论(0编辑  收藏  举报