• 面试题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;
    }
    
    
  • 相关阅读:
    Node 命令行工具 commander.js 快速上手
    使用 express 极简处理前端路由的 history 模式问题
    在博客中插入希沃白板课件
    休息一下(屏幕提醒)
    vue htmlWebpackPlugin.options.title 标题设置
    使用 docker 部署 elasticsearch 并安装 ik 中文分词器
    .NET 中的计时 tick 是多长?
    剑指offer队列的最大值(主队列+辅助队列)
    Golang垃圾回收原理解析
    Golangchannel底层实现精要
  • 原文地址:https://www.cnblogs.com/flyingrun/p/13526160.html
Copyright © 2020-2023  润新知