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

2025-05-27 0 89

设计一个找到数据流第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大元素的计算方法内容请搜索快网idc以前的文章或继续浏览下面的相关文章希望大家以后多多支持快网idc!

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

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 php数据流中第K大元素的计算方法及代码分析 https://www.kuaiidc.com/70240.html

相关文章

发表评论
暂无评论