44、PHP 实现数据流中的中位数(含源码)

题目: PHP 实现数据流中的中位数

描述:

如何得到一个数据流中的中位数?

如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。

如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。

php 复制代码
<?php

$bigTop = new SplMaxHeap();
$smallTop = new SplMinHeap();
 
function Insert($num)
{
    // write code here
    global $bigTop;
    global $smallTop;
    //保证小顶堆的数 都大于大顶堆的数 其实就是小顶堆的顶 大于大顶堆的顶
    if($smallTop->isEmpty() || $num >= $smallTop->top()){
        $smallTop->insert($num);
    }else{
        $bigTop->insert($num);
    }
    if($smallTop->count() == $bigTop->count() + 2) $bigTop->insert($smallTop->extract());
    if($smallTop->count() + 1 == $bigTop->count()) $smallTop->insert($bigTop->extract());
}
function GetMedian(){
    // write code here
    global $bigTop;
    global $smallTop;
    return $smallTop->count() == $bigTop->count() ? ($smallTop->top() + $bigTop->top())/2 : $smallTop->top();
}
相关推荐
砖厂小工1 小时前
Compose 中函数引用 vs Lambda:到底该用哪个?
android
Kapaseker11 小时前
详解 Compose background 的重组陷阱
android·kotlin
黄林晴12 小时前
Kotlin 2.3.20-RC2 来了!JPA 开发者狂喜,6 大更新一文速览
android·kotlin
kymjs张涛1 天前
OpenClaw 学习小组:初识
android·linux·人工智能
ServBay1 天前
告别面条代码,PSL 5.0 重构 PHP 性能与安全天花板
后端·php
范特西林1 天前
实战演练——从零实现一个高性能 Binder 服务
android
范特西林1 天前
代码的生成:AIDL 编译器与 Parcel 的序列化艺术
android
范特西林1 天前
深入内核:Binder 驱动的内存管理与事务调度
android
范特西林1 天前
解剖麻雀:Binder 通信的整体架构全景图
android
范特西林1 天前
破冰之旅:为什么 Android 选择了 Binder?
android