zoukankan      html  css  js  c++  java
  • PHP代码实现TopN

    在一堆数据中按分数值由大到小取前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
            )
    
    )
    */
    
  • 相关阅读:
    Jquery fancybox 可以实现在当前页面弹出框
    http下载
    使用Fat 直接运行Java中自定义的main方法
    Tomcat 中配置直接请求(不带项目名请求)
    java 解压
    文件压缩到zip
    导出excel 头部文件
    NPOI 动态添加行
    ICSharpCode.SharpZipLib.Zip.ZipException: EOF in header
    elasticsearch配置
  • 原文地址:https://www.cnblogs.com/RainCry/p/13225622.html
Copyright © 2011-2022 走看看