php数据流中第K大元素的计算方法及代码分析

吾爱主题 阅读:123 2021-11-21 17:14:00 评论:0

设计一个找到数据流中第K大元素的类(class)。注意是排序后的第K大元素,不是第K个不同的元素。

计算方法

1、直接使用最小堆,堆的大小为 k,这样保证空间占用最小,最小堆的根节点是就是最小值,也是我们想要的结果。

2、php的spl标准库是有最小堆这个库,直接在代码中继承SplMinHeap。

实例

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 class KthLargest extends SplMinHeap {        /**      * @param Integer $k      * @param Integer[] $nums      */      static $nums ;      public $k ;      function __construct( $k , $nums ) {          $this ->k = $k ;          // 遍历初始化数组,分别插入堆中          foreach ( $nums as $v ) {              $this ->add( $v );          }      }          * @param Integer $val      * @ return Integer      function add( $val ) {         // 维持堆的大小为k,当堆还未满时,插入数据。          if ( $this -> count () < $this ->k) {              $this ->insert( $val );          } elseif ( $this ->top() < $val ) {          // 当堆满的时候,比较要插入元素和堆顶元素大小。大于堆顶的插入。堆顶移除。              $this ->extract();          return $this ->top();      }}      * Your KthLargest object will be instantiated and called as such:      * $obj = KthLargest( $k , $nums );      * $ret_1 = $obj ->add( $val );

实例扩展:

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 class KthLargest {      /**       * @param Integer $k       * @param Integer[] $nums       */      static $nums ;      public $k ;      function __construct( $k , $nums ) {          $this ->k = $k ;          $this ->nums = $nums ;      }         /**       * @param Integer $val       * @return Integer       */      function add( $val ) {          array_push ( $this ->nums, $val );          rsort( $this ->nums);          return $this ->nums[ $this ->k - 1];      } }

第一个思路,时间超限的原因是每次都要对$this->nums这个数组,进行重新排序,上次已经排序好的,还要再重新排一次,浪费时间。所以,下面的解法是,每次只保存,上次排序完的前k个元素。这次的进行排序的次数就减少了。时间也减少了。

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 class KthLargest {      /**       * @param Integer $k       * @param Integer[] $nums       */      static $nums ;      public $k ;      function __construct( $k , $nums ) {          $this ->k = $k ;          $this ->nums = $nums ;      }         /**       * @param Integer $val       * @return Integer       */      function add( $val ) {          array_push ( $this ->nums, $val );          rsort( $this ->nums);          $this ->nums = array_slice ( $this ->nums, 0, $this ->k);                   return $this ->nums[ $this ->k - 1];      } }

到此这篇关于php数据流中第K大元素的计算方法及代码分析的文章就介绍到这了,更多相关php数据流中第K大元素的计算方法内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://www.py.cn/php/jiaocheng/31516.html

可以去百度分享获取分享代码输入这里。
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

【腾讯云】云服务器产品特惠热卖中
搜索
标签列表
    关注我们

    了解等多精彩内容