内容简介:本题目借助快排思想,算法描述:代码:算法复杂度分析:
本题目借助快排思想,算法描述:
- a为待 排序 数组,n为数组长度
-
问题转换:把第k大数字转换成第l小数字,比如:
n=5,k=1
,那么l=n-k+1=5
,也就是第5小的数字,其下标l_i=5-1=4
。 -
取
a[n-1]
作为 pivot -
用快排的思路,把
< pivot
的元素放到 pivot 左边,把>= pivot
的元素放到 pivot 右边,得到pivot的下标:pivot_i
-
如果
pivot_i < l_i
,则说明被查找的数字可能在右边,对右边重复2-5步骤 -
如果
pivot_i > l_i
,则说明被查找的数字可能在左边,对左边重复2-5步骤
代码:
public static int findKthBigNumber(int[] a, int kthBig) { int n = a.length; int lthSmall = n - kthBig; return quickFind(a, 0, a.length - 1, lthSmall); } private static int quickFind(int[] a, int start, int end, int lthSmall) { if (start > end) { return -1; } int pivot = a[end]; int pivot_i = start; for (int j = start; j <= end - 1; j++) { if (a[j] < pivot) { int tmp = a[j]; a[j] = a[pivot_i]; a[pivot_i] = tmp; pivot_i++; } } a[end] = a[pivot_i]; a[pivot_i] = pivot; if (pivot_i == lthSmall) { return a[pivot_i]; } if (pivot_i < lthSmall) { return quickFind(a, pivot_i + 1, end, lthSmall); } return quickFind(a, start, pivot_i - 1, lthSmall); }
算法复杂度分析:
最好情况:
k > n
最坏情况:
(n-1)+(n-2)+(n-3)+...+1=n(n-1)/2
平均情况:
- 不知怎么分析
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Windows黑客编程技术详解
甘迪文 / 人民邮电出版社 / 2018-12 / 108
《Windows黑客编程技术详解》介绍的是黑客编程的基础技术,涉及用户层下的Windows编程和内核层下的Rootkit编程。本书分为用户篇和内核篇两部分,用户篇包括11章,配套49个示例程序源码;内核篇包括7章,配套28个示例程序源码。本书介绍的每个技术都有详细的实现原理,以及对应的示例代码(配套代码均支持32位和64位Windows 7、Windows 8.1及Windows 10系统),旨在......一起来看看 《Windows黑客编程技术详解》 这本书的介绍吧!