algorithm - 前 k 个最大元素插入 O(logn) 和 O(k) 的数据结构
问题描述
我在数据结构类中被要求找到适合这些需求的数据结构:
Insert(S,num) - Insert to S a num in a O(log(n)) complexion time
PrintMax_k(S) - Print the k (constant) first biggest elemnts in some order(doesnt matter) in a O(k) complexion time
PrintAll(S) - Print all elemnts in some order(doesnt matter) in a O(n) complexion time
我需要使用什么类型的数据结构?
解决方案
由于k被假定为常数,您可以将此数据结构创建为包含H
最多k个元素的最小堆(在数组数据结构中实现)和具有A
任意顺序的剩余元素(如果有)的标准数组的组合.
操作如下:
Insert(S,num):
if size(H) < k:
H.insert(num)
else if H[0] < num: # compare with root value of heap, which is its minimum, at index 0
A.append(H[0])
H[0] := num # replace root value
H.heapify() # sift down num, so heap property is restored
else:
A.append(num)
有关堆的 insert 和 heapify 方法的实现,请参阅Wikipedia 上的Binary Heap或其他地方。
在任何调用之后Insert
,H
将插入迄今为止的k个最大值。任何溢出(较小的值)都将在A
.
PrintMax_k(S):
for i in 0..size(H)-1: # simply iterate over the heap (which is an array)
print H[i]
最后:
PrintAll(S):
PrintMax_k(S) # call the above function
for i in 0..size(A)-1:
print A[i]
推荐阅读
- python - 如何扫描数组中与查询词具有最长共享前缀的元素?
- spring - 是否可以为spring cloud gateway中的所有请求配置全局超时
- automation - 如何使用访客帐户仅输入密码以登录 Windows 10?
- c# - 如何在服务器端获取调用的 webservice.asmx 的方法名称
- html - 无法在浏览器 html 中显示控制台日志结果
- templates - Concourse-CI 模板文件
- unix - 当我使用 telnet 协议连接到服务器时,我收到错误“无法打开与主机的连接,连接失败”
- spring - ApplicationEventPublisher 在使用 WebApplicationContext 的过滤器中不能用作 Bean
- excel - Excel sumif 返回大数字而不是零
- neural-network - 哪种神经网络架构可以为文本分类提供更好的准确性?