当前位置 博文首页 > php数据流中第K大元素的计算方法及代码分析

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

    作者:小妮浅浅 时间:2021-08-15 18:49

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

    计算方法

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

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

    实例

    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);

    实例扩展:

    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个元素。这次的进行排序的次数就减少了。时间也减少了。

    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];
        }
    }
    jsjbwy