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();
}
相关推荐
Mars-xq1 小时前
Android godot 交互数据监听
android·godot·交互
_李小白1 小时前
【Android FrameWork】延伸阅读: PowerManagerService
android
万岳软件开发小城1 小时前
医疗陪诊软件源码开发方案解析:预约、派单、陪诊全流程如何实现
php·软件开发·医院陪诊系统源码·陪诊app开发·陪诊软件开发
_李小白1 小时前
【Android 性能分析】第四天:CPU Profiler
android
lxysbly1 小时前
nes模拟器安卓版下载汉化版2026
android
薛定谔的猫19821 小时前
RAG(四) LangChain 使用PyPDFLoader加载 PDF 并实现内容总结功能
langchain·pdf·php
YIN_尹1 小时前
【MySQL】库的操作
android·数据库·mysql
DeepFlow 零侵扰全栈可观测2 小时前
民生银行云原生业务的 eBPF 可观测性建设实践
运维·开发语言·分布式·云原生·金融·php
2501_915921432 小时前
如何将 iOS 应用的 IPA 文件安装到手机进行测试
android·ios·智能手机·小程序·uni-app·iphone·webview