查找问题整理(2)查找第K大的数Kth Order Statitic
来源:互联网 发布:气象站点数据下载 编辑:程序博客网 时间:2024/05/18 00:15
借助快速排序的思路,可以实现一种查找算法, Kth Order Statistic,即给定一个未排序的数组,找到数组中第K大的数。
注意这个Kth Order Statistic和top K算法有区别。Top K算法是找到前K大的数,要找K个数。而Kth Order Statistic 是找到第K大的数,只找1个数。
//借助快速排序中的partition函数int partition_kth(int* arr, int st, int ed){ int j=st; int i=j-1; int pivot=arr[ed]; int temp; while (j<=ed-1) { if (pivot>arr[j]) { i++; temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } j++; } i++; temp=arr[ed]; arr[ed]=arr[i]; arr[i]=temp; return i;}
函数主要算法如下,使用了递归的思路
//Kth Order Statistic算法int kth_order_statistic(int* arr, int st, int ed, int order){ int attemp_order = partition_kth(arr,st,ed); int temp1 = attemp_order -st+1; if (temp1 == order) return arr[attemp_order]; else if ( temp1 < order) kth_order_statistic(arr, attemp_order+1, ed, order-temp1); //NOTE1:不是 kth_order_statistic(arr, attemp_order+1, ed, order); //NOTE2:Kth Order是一个和长度一致的变量,不是一个刻度变量。 else kth_order_statistic(arr, st, attemp_order-1, order);}它的main函数如下
int main(){int unsorted_arr[10]={10,7,9,6,8,4,11,15,1,5}; std::cout<<kth_order_statistic(unsorted_arr,0,9,1)<<std::endl; std::cout<<kth_order_statistic(unsorted_arr,0,9,7)<<std::endl; std::cout<<kth_order_statistic(unsorted_arr,0,9,9)<<std::endl;return 0;}返回结果分别是数组中第1,7,9大的数。
- 查找问题整理(2)查找第K大的数Kth Order Statitic
- LeetCode 二分查找第K大的数215. Kth Largest Element in an Array
- 查找第k大的数
- 230. Kth Smallest Element in a BST | 二叉排序树中查找第K小的数
- 查找数组中第K大的数
- 查找N个数中第K大的数
- 查找给定区间内第K大/小的数
- 查找N个数中第K大的数
- O(n)查找第k小(大)的数
- 查找 Kth 小的数
- 查找前k大的数
- 查找前K大的数
- DSOJ Kth Number(第k大的数)
- 378. Kth Smallest Element in a Sorted Matrix(查找矩阵中第k小的数)
- 查找第K大的数据
- 查找--第K大的元素
- 查找第K大的元素
- 查找第 k 大的元素
- python 时间
- Android app 使用webview
- CountDownLatch实现主线程等待所有子线程运行结束后再继续执行的实现
- 基于单片机的电子密码锁的实现
- 关于MongoDB的group分组
- 查找问题整理(2)查找第K大的数Kth Order Statitic
- hdu 1754
- 随便写写
- 7个高级技巧帮助你释放大量Mac OS X硬盘空间
- Lucene的多域查询、结果中查询、查询结果分页、高亮查询结果和结果评分
- 基于单片机的生日快乐歌
- (ubuntu)在andorid andk工程中使用ccache加速编译速度
- 要害词排名稳固的要端
- [微笑] 三十六计