当前位置:网站首页>Top - k问题
Top - k问题
2022-06-11 21:36:00 【爱学代码的学生】
什么是Top - k问题?
比如:专业前10名、世界500强、富豪榜、游戏中前100的活跃玩家等。
对于Top-K问题,能想到的最简单直接的方式就是排序,但是:如果数据量非常大,排序就不太可取了(可能数据都不能一下子全部加载到内存中)。
最佳的方式就是用堆来解决,基本思路如下:
1. 用数据集合中前K个元素来建堆前k个最大的元素,则建小堆,前k个最小的元素,则建大堆
2. 用剩余的N-K个元素依次与堆顶元素来比较,不满足则替换堆顶元素。
代码实现如下:
//用堆来解决topk问题
void PrintTopK(int* a, int n, int k)
{
int i,j;
// 1. 建堆--用a中前k个元素建堆
int parent=(k-1)/2;
for(i=parent;i>=0;i--){
AdjustDown(a,i,k);
}
// 2. 将剩余n-k个元素依次与堆顶元素交换,不满则则替换
for(i=k+1;i<n;i++){
if(a[i]>a[0]){
swap(a,0,i);
AdjustDown(a,0,k);
}
}
for(i=0;i<k;i++){
printf("%d ",a[i]);
}
}
void TestTopk()
{
int n = 10000;
int* a = (int*)malloc(sizeof(int)*n);
srand(time(NULL));
for (size_t i = 0; i < n; ++i)
{
a[i] = rand() % 1000000;
}
a[5] = 1000000 + 1;
a[1231] = 1000000 + 2;
a[531] = 1000000 + 3;
a[5121] = 1000000 + 4;
a[115] = 1000000 + 5;
a[2335] = 1000000 + 6;
a[9999] = 1000000 + 7;
a[76] = 1000000 + 8;
a[423] = 1000000 + 9;
a[3144] = 1000000 + 10;
PrintTopK(a, n, 10);
}最终得到我们要的数:

边栏推荐
猜你喜欢

【历史上的今天】6 月 11 日:蒙特卡罗方法的共同发明者出生;谷歌推出 Google 地球;谷歌收购 Waze
![[Part 15] use and basic principle of forkjoinpool [key]](/img/36/e21b16ec92d444149bc793f340f9f3.jpg)
[Part 15] use and basic principle of forkjoinpool [key]

Leetcode-129- sum of numbers from root node to leaf node

2021牛客多校5 Double Strings

LeetCode-129-求根节点到叶节点数字之和
![[Part 14] source code analysis and application details of completionservice class [key]](/img/41/9f5383d6eafb32723e29c15da3a1af.jpg)
[Part 14] source code analysis and application details of completionservice class [key]

多态的所有特征

Jenkins+allure integrated report construction

LeetCode-104-二叉树的最大深度

189. 轮转数组
随机推荐
RPA+低代码为何是加速财务数字化转型之利器?
Building a custom CNN model: identifying covid-19
Common file functions
Flutter series: detailed explanation of container layout commonly used in flutter
In the post epidemic era, how can enterprise CIOs improve enterprise production efficiency through distance
zypper命令使用示例
RPA super automation | nongnongji and cloud expansion accelerate financial intelligent operation
JVM | virtual machine stack (local variable table; operand stack; dynamic link; method binding mechanism; method call; method return address)
[Part 15] use and basic principle of forkjoinpool [key]
Customer information management software
Experiment 10 Bezier curve generation - experiment improvement - control point generation of B-spline curve
如何使用事物码 SAT 查找某个 SAPGUI 屏幕字段对应的后台存储数据库表的名称试读版
Leetcode-32- longest valid bracket
每日一题 -- 验证回文串
即将首发 | 业界首个零售数字化创新白皮书,解锁全链路数字化致胜秘籍
Leetcode-322- change exchange
[Part 13] source code analysis and application details of completabilefuture class [key]
AC automata
BZOJ3189 : [Coci2011] Slika
[Part 14] source code analysis and application details of completionservice class [key]