设计一个找到数据流中第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
相关文章
猜你喜欢
- ASP.NET本地开发时常见的配置错误及解决方法? 2025-06-10
- ASP.NET自助建站系统的数据库备份与恢复操作指南 2025-06-10
- 个人网站服务器域名解析设置指南:从购买到绑定全流程 2025-06-10
- 个人网站搭建:如何挑选具有弹性扩展能力的服务器? 2025-06-10
- 个人服务器网站搭建:如何选择适合自己的建站程序或框架? 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-05-25 92
-
2025-05-27 15
-
2025-06-04 58
-
2025-05-25 28
-
2025-05-25 12
热门评论