class MaxHeap extends SplHeap{
public function compare($value1, $value2) {
return ($value1 - $value2);
}
public function GetKMinNum($arr, $k){
if(is_array($arr) && $k > 0){
$count = count($arr);
for($i=0; $i<$count; $i++){
if($i < $k){
$this->insert($arr[$i]);
}else{
$top = $this->top();
if($top > $arr[$i]){
$this->extract();
$this->insert($arr[$i]);
}
}
}
}
return $this;
}
}$heap = new MaxHeap();
$arr = array();
for($i=0; $i<100000; $i++){
$arr[] = rand(100, 1000000);
}
$min = $heap->GetKMinNum($arr, 7);
foreach($min as $val){
echo $val . '<br/>';
}以上就介绍了PHP 利用SPL标准库获取数组中最小的K个值,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号