博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
程序员面试金典--取前K小的数
阅读量:4686 次
发布时间:2019-06-09

本文共 997 字,大约阅读时间需要 3 分钟。

程序员面试金典--取前K小的数

 

给定 n, k 和 n个不同的数字,取前k小个数。

输入:

7 2

7 9 3 2 12 4 8

输出: 

2 3

 

使用堆排序,可以达到O(n) 的时间复杂度。

 

#include 
const int MAXN = 10000 + 10;int n, k, cnt, num[MAXN], a[MAXN], ans[MAXN]; void AdjustHeap(int x){ int idx = x; int lchild = 2*x + 1; int rchild = 2*x + 2; if(idx < k){ if(lchild < k && a[idx] < a[lchild]){ idx = lchild; } if(rchild < k && a[idx] < a[rchild]){ idx = rchild; } if(idx != x){ int tmp = a[idx]; a[idx] = a[x]; a[x] = tmp; AdjustHeap(idx); } }} int main(){ freopen("in.txt", "r", stdin); while(scanf("%d %d", &n, &k) != EOF){ for(int i=0; i
=0; --i){ AdjustHeap(i); } for(int i=k; i
num[i]){ a[0] = num[i]; AdjustHeap(0); } } cnt = 0; for(int i=k-1; i>=0; --i){ ans[cnt++] = a[0]; a[0] = a[i]; AdjustHeap(0); } for(int i=cnt-1; i>0; --i){ printf("%d ", ans[i]); } printf("%d\n", ans[0] ); } return 0; }

  

 

转载于:https://www.cnblogs.com/zhang-yd/p/7567125.html

你可能感兴趣的文章
数组 Arrays类
查看>>
String类的深入学习与理解
查看>>
OLTP vs OLAP
查看>>
一些题目(3)
查看>>
Eclipse下配置主题颜色
查看>>
杂题 UVAoj 107 The Cat in the Hat
查看>>
ftp sun jdk自带
查看>>
python 元类——metaclass
查看>>
什么是缓冲,引入缓冲的原因是什么?
查看>>
叙述下列术语的定义并说明它们之间的关系:卷、块、文件、记录。
查看>>
不把DB放进容器的理由
查看>>
OnePage收集
查看>>
Gym - 101492I 区间限制费用流
查看>>
Entity Framework技巧系列之九 - Tip 35 - 36
查看>>
2808 sci 接收中断
查看>>
原创:机器学习排序深入解读
查看>>
HDU 4288
查看>>
程序的跳转(一行代码)
查看>>
hello world ,详解
查看>>
Update
查看>>