数组中找出第k大的值

最简单的办法,就是先排序,然后把第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 array public 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 pivot return startIndex; }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值