数组中找出第k大的值
来源:互联网 发布:python microservice 编辑:程序博客网 时间:2024/05/09 00:50
最简单的办法,就是先排序,然后把第K个值找出来,这样算法的复杂度为 O(nlgn).
其实还有一种更简单的方法,其平均复杂度 为 O(lgn),当然,最坏是 O(n^2). 这种算法就是利用了 quicksort 和二分查找 的做法。先把数组分成两个部分,左边一个部分比pivot小,另一边比pivot大。然后再观察pivot的位置,如果pivot的位置比 K大,那么那个第K个值就一定在pivot的左边,同理,可得其它情况。
public void findKthLargest(int left, int right, int[] array, int k) {int tempK = partition(left, right, array);if (tempK == k-1){System.out.println(array[tempK]);} else if (tempK > k-1) {findKthLargest(left, tempK-1, array, k);} else {findKthLargest(tempK+1, right, array, k);}}// partition the arraypublic int partition(int left, int right, int[] array) {Random rd = new Random();int pivot = rd.nextInt(right - left + 1) + left ;exchange(pivot, right, array);int startIndex = left;for (int tempIndex = left; tempIndex < right; tempIndex++) {if (array[tempIndex] < array[right]) {exchange(tempIndex, startIndex, array);startIndex++;} }exchange(right, startIndex, array);//the index of the pivotreturn startIndex;}
- 数组中找出第k大的值
- 数组中找出第k大的值
- 找出数组中第K大的数值
- 找出数组中第K大的数
- 找出数组中第k大的数
- 找出数组中第 K 大的数
- 找出第K大的数<数组>
- 找出大数组array中第k大的元素(要求时间复杂度O(1))
- 算法(三)找出数组中第K大元素
- 无序数组找出其中的第K大的数
- 数组中找出第二个最大的元素(第k大的元素)
- 数组试题---找出第k大的数
- 找出数组中的第K大的元素
- 面试题—— 找出一个无序整型数组中第k大的数。
- 算法之每日一题:找出无序数组中第k大的数字
- 利用快速排序思想找出数组中第K大的数
- 利用快排思想找出数组中第k大的元素
- java 实现从无序数组中 找出第k大的数, 无序数组充许有重复元素
- 哄
- 为什么Google要执行严格的代码编写规范
- 自己动手重新实现LINQ to Objects: 1 - 引言
- [Android]为指定的应用创建桌面快捷方式
- Handler
- 数组中找出第k大的值
- oracle中spool的用法小结
- [Android]挂断、接听电话
- ASP.NET Internals – IIS and the Process Model (IIS5, IIS6)
- 通过AIDL及反射机制,使用隐藏API挂断电话
- Struts2与Spring整合
- Introduction to IIS 7 Architecture
- 关于java几种提交方式
- Windows虚拟主机完美实现wordpress伪静态终极方法