有一个整数数组,请你根据快速排序的思路,找出数组中第K大的数。

给定一个整数数组a,同时给定它的大小n和要找的K(K在1到n之间),请返回第K大的数,保证答案存在。

测试样例:

[1,3,5,2,2],5,3

返回:2
 
投机取巧能通过:
 class Finder {
public:
int findKth(vector<int> a, int n, int K) {
// write code here
sort(a.begin(), a.end());
return a[n - K];
}
};

用快排思想:

 #include <iostream>
#include <vector>
#include <string>
#include <queue>
#include <stack>
#include <unordered_map>
#include <map>
#include <algorithm>
using namespace std; //用快排的思想:例如找49个元素里面第24大的元素,那么按如下步骤:
//1.进行一次快排(将大的元素放在前半段,小的元素放在后半段), 假设得到的中轴为p
//2.判断 p - low == k -1,如果成立,直接输出a[p],(因为前半段有k - 1个大于a[p]的元素,故a[p]为第K大的元素)
//3.如果 p - low > k-1, 则第k大的元素在前半段,此时更新high = p - 1,继续进行步骤1
//4.如果 p - low < k-1, 则第k大的元素在后半段,此时更新low = p + 1, 且 k = k - (p - low + 1),继续步骤1.
//由于常规快排要得到整体有序的数组,而此方法每次可以去掉“一半”的元素,故实际的复杂度不是o(nlgn), 而是o(n)。
class Finder {
public:
int partation(vector<int>& a, int low, int high) {
int key = a[low];
while (low < high) {
while (low < high && a[high] <= key)
high--;
a[low] = a[high];
while (low < high && a[low] >= key)
low++;
a[high] = a[low];
}
a[low] = key;
return low;
}
int findKth(vector<int>& a, int low, int high, int k)
{
int part = partation(a, low, high);
if (k == part - low + )
return a[part];
else if (k > part - low + )
return findKth(a, part + , high, k - part + low - );
else
return findKth(a, low, part - , k); }
int findKth(vector<int> a, int n, int K) {
// write code here
return findKth(a, , n - , K);
}
}; //测试
int main()
{
vector<int> v{ ,,,, };
Finder solution;
cout<<solution.findKth(v, , );
}

最新文章

  1. javaWeb高级编程(1)
  2. Quartz2D之绘制一个简单的机器猫
  3. ReferenceQueue&lt;T&gt;随笔
  4. 【WP 8.1开发】一键锁屏
  5. 搜索表头的例子-jqueryEasyUi
  6. spring整合httpclient
  7. swoole 安装
  8. 整合ssh model $$_javassist_13 cannot be cast to javassist.util.proxy.Proxy
  9. 153. Find Minimum in Rotated Sorted Array
  10. PHP中$_SERVER获取当前页面的完整URL地址
  11. InnoDB这种行锁实现特点意味者:只有通过索引条件检索数据,InnoDB才会使用行级锁,否则,InnoDB将使用表锁!
  12. THREE.JS + Blender(obj、mtl加载代码)
  13. C++实现二叉树的基本操作
  14. 浅谈JNDI的使用
  15. lua的前景??
  16. java--随机数的产生
  17. Nginx教程(一) Nginx入门教程
  18. 精进之路之CAS
  19. 【SpringMVC】关于classpath和contextConfigLocation
  20. python中字符串的几种表达方式(用什么方式表示字符串)

热门文章

  1. Win7安装了Visual Studio 2008没有快捷方式怎么办
  2. Linux Java开发环境
  3. MySql RESTRICT CASCADE SET NULL
  4. ASP.NET中的配置文件
  5. 工作总结 sql 中过滤条件 中的 (where中的) and
  6. Https单向认证和双向认证介绍
  7. [转] java代码块 介绍
  8. php数组操作,内容相同,键值不同,互换
  9. 【已解决】ckfinder_php_3.4.4 IIS 报错 无效请求
  10. iOS 渐变色实现,渐变色圆环,圆环进度条