首页 > Web开发 > 详细

PHP代码实现TopN

时间:2020-07-02 16:49:17      阅读:63      评论:0      收藏:0      [点我收藏+]

在一堆数据中按分数值由大到小取前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 = $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
        )

)
*/

PHP代码实现TopN

原文:https://www.cnblogs.com/RainCry/p/13225622.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!