zoukankan      html  css  js  c++  java
  • 剑指offer(63)数据流中的中位数

    题目描述

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

    题目分析

    不同的数据结构对应着不同的解法,平时做题的时候要时刻想着该选用什么数据结构

    数据结构 插入的时间复杂度 得到中位数的时间复杂度
    没有排序的数组 O(1) O(n)
    排序的数组 O(n) O(1)
    排序链表 O(n) O(1)
    二叉搜索树 平均O(logn),最差O(n) 平均O(logn),最差O(n)
    AVL树 O(logn) O(1)
    最大堆和最小堆 O(logn) O(1)

    代码

    这里只给出下第二种方法,就是插入的时候保持数组一直有序。

    const array = [];
    function Insert(num) {
      array.push(num);
      for (let i = array.length - 2; array[i] > num; i--) {
        [array[i], array[i + 1]] = [array[i + 1], array[i]];
      }
    }
    function GetMedian() {
      if (array.length & 1 === 1) {
        return array[(array.length - 1) / 2];
      }
      return (array[array.length / 2] + array[array.length / 2 - 1]) / 2;
    }
  • 相关阅读:
    Linux中/etc目录下passwd和shadow文件
    Linux基本命令
    Linux目录结构说明与基本操作
    如何用虚拟机VMware Workstation安装CentOs-7
    VPP源码分析及流程图
    VPP环境搭建及配置
    【转】智能指针的交叉引用问题及解决方法
    二叉树的前 中 后 层序遍历
    排序算法
    C和C++的一些区别
  • 原文地址:https://www.cnblogs.com/wuguanglin/p/GetMedian.html
Copyright © 2011-2022 走看看