数组中找出第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;}



原创粉丝点击