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();
}
相关推荐
ooseabiscuit2 小时前
Laravel 8.x核心特性深度解析
php·laravel
赏金术士5 小时前
Kotlin ViewModel
android·kotlin
vistaup6 小时前
kotlin 二维码实现高斯模糊
android·kotlin
愈努力俞幸运7 小时前
function calling与mcp
android·数据库·redis
阿巴斯甜8 小时前
LeakCanary
android
阿巴斯甜8 小时前
compose
android
阿巴斯甜8 小时前
Glide
android
-SOLO-8 小时前
使用Perfetto debug trace查看超时slice
android
阿巴斯甜8 小时前
Retrofit
android
阿巴斯甜9 小时前
OkHttp
android