在一堆資料中按分數值由大到小取前N個資料,用小根堆的方法來實作,具體代碼如下:
<?php
class TopN extends SplMinHeap
{
private $top_n;
/**
* @param int $top_n 前top_n名
*/
public function __construct($top_n)
{
$this->top_n = $top_n;
}
/**
* 添加一個元素
* @param number $score 排序值
* @param mixed $value 元素
*/
public function add($score,$value)
{
if ($this->top_n) {
$this->insert(array($score,$value));
$this->top_n--;
} else {
$top = $this->top();
if ($top[0] < $score) {
$this->extract();
$this->insert(array($score,$value));
}
}
}
/**
* 獲取topN的結果
* @return array
*/
public function getResult()
{
$list = array();
while ($this->valid()) {
$value = https://www.cnblogs.com/RainCry/p/$this->current();
$list[] = $value[1];
$this->next();
}
return array_reverse($list);
}
}
$mTopN = new TopN(3);
$mTopN->add(70,array('name'=>'張三','score'=>70));
$mTopN->add(80,array('name'=>'李四','score'=>80));
$mTopN->add(100,array('name'=>'王五','score'=>100));
$mTopN->add(90,array('name'=>'趙六','score'=>90));
$result = $mTopN->getResult();
print_r($result);
/*
Array
(
[0] => Array
(
[name] => 王五
[score] => 100
)
[1] => Array
(
[name] => 趙六
[score] => 90
)
[2] => Array
(
[name] => 李四
[score] => 80
)
)
*/
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/13942.html
標籤:PHP
