有一个整数数组,请你根据快速排序的思路,找出数组中第K大的数。
给定一个整数数组a,同时给定它的大小n和要找的K(K在1到n之间),请返回第K大的数,保证答案存在。
测试样例:
[1,3,5,2,2],5,3

http://blog.csdn.net/hymanxq/article/details/51026818

public class 寻找第K大的数 {

    public static void main(String[] args) {
// TODO Auto-generated method stub
int[] a = { , , , , }; System.out.println(findKth(a, a.length, ));
/*
* qsort(a, 0, a.length-1); for(int i:a){ System.out.print(i+" "); }
*/
} public static int findKth(int[] a, int n, int K) {
// write code here return qs(a, , a.length - , a.length - K); // 第K大数 的下标
} static void qsort(int[] a, int left, int right) {
if (left < right) {
int p = partition(a, left, right);
qsort(a, left, p - );
qsort(a, p + , right);
}
} static int qs(int[] a, int left, int right, int k) {
// if (left < right)
{
int p = partition(a, left, right);
if (p == k) {
return a[p];
} else if (p > k)
return qs(a, left, p - , k);
else
return qs(a, p + , right, k);
}
} static int partition(int[] a, int left, int right) {
int p = a[left]; while (left < right) {
while (left < right && a[right] >= p) {
right--;
}
if (left < right) {
a[left++] = a[right];
} while (left < right && a[left] <= p) {
left++;
}
if (left < right) {
a[right--] = a[left];
}
}
a[left] = p;
return left;
}
}

最新文章

  1. jQuery对表格的操作及其他应用
  2. JS前台base32加密,C#后台解码
  3. CSS3简单动画
  4. Linux下MySQL忘记密码
  5. 让你的APP支持iPhone5
  6. [游戏模版6] Win32 graph
  7. 【AdaBoost算法】强分类器训练过程
  8. Spring Boot 3 Hibernate
  9. (转)C#调用非托管Win 32 DLL
  10. [置顶] myEclipse8.5或者eclipse手工安装jd插件(myEclipse8.5或eclipse内直接查看.class文件,jd反编译工具)
  11. 标题:a++和++a的区别
  12. 单源最短路径问题-Dijkstra算法
  13. Java I/O---获取文件目录并写入到文本
  14. 《并行程序设计导论》——Pthreads
  15. 三大家族(offset、scroll、client)
  16. XVII Open Cup named after E.V. Pankratiev. GP of Tatarstan
  17. 图解 (a + b) * (a + b) == a**2 + 2*a*b + b**2
  18. HNOI2019 游记
  19. SSD垃圾回收
  20. 22状态模式State

热门文章

  1. Spring IoC底层原理
  2. AFNetworking 不支持 text/plain,unacceptable content-type: text/plain
  3. curl传post数据流
  4. qt学习(二) buttong layout spinbox slider 示例
  5. BFS入门
  6. CoderForces 518C Anya and Smartphone (模拟)
  7. metasploit-数据库支持
  8. csdn的blog可以直接导入内含图片的word文档吗?
  9. shell 脚本 查看班上同学的网络状态
  10. Give $20/month and provide 480 hours of free education