目录
预备知识:
1题目来源
https://www.nowcoder.com/questionTerminal/e016ad9b7f0b45048c58a9f27ba618bf
2题目描述
有一个整数数组,请你根据快速排序的思路,找出数组中第K大的数。
给定一个整数数组a,同时给定它的大小n和要找的K(K在1到n之间),请返回第K大的数,保证答案存在。
测试样例:
[1,3,5,2,2],5,3
返回:2
所谓的第K大也就是第几个最大的数,比如:测试用例中第2大(k=2),表示第二个最大的数,为3
3分析
a.进行一次快排,将大的元素放在前半段,小的元素放在后半段,假设得到中轴(基准)tmp
public static int partion(int[] array,int low,int high){
// 将数组的首元素作为每一轮比较的基准
int tmp=array[low];
while(low<high){
while(low<high&&array[high]<=tmp){//从右往左找比tmp大的
high--;
array[low]=array[high];
}
while (low<high&&array[low]>=tmp){//从左往右找比tmp小的
low++;
array[high]=array[low];
}
}
array[low]=tmp;
return low;
}
b.findkth()方法,判断tmp-low+1==k
1tmp-low+1==k,返回array[tmp]
2tmp-low+1<k, 向基准右边递归找,范围从tmp+1->high注意:此时的k值不是初始k需要减去基准左半边的部分,
此时的k=k-(tmp-low+1)
3tmp-low+1>k,向基准左边递归找,范围从low->tmp-1
public int findkth(int[] array,int low,int high,int k){
int tmp=partion(array);
if(tmp-low+1==k){
return array[tmp];
}else if(tmp-low+1<k){
return findkth(array,tmp+1,high,k-(tmp-low+1));
}return findkth(array,low,tmp-1,k);
}
c.写一个findkth()重载上面的方法,为了初始化(low=0,high=n-1)和调用,n=array.length()
public int findkth(int[] array,int n,int k){//n=array.length()
findkth(array,0,n-1,k);
}
4完整代码
public class Finder {
public int findKth(int[] a,int n,int k){
//初始化low=0;high=n-1
return findKth(array,0,n-1,k);
}
public int findKth(int[] a,int low,int high,int k){
int par=partation(a,low,high);
if(par-low+1==k){//第k个最大数就是基准数
return a[par];
}else if(par-low+1<k) {//向右递归找k,范围从par+1到high
return findKth(array,par+1,high,k-(par-low+1));
}
return findKth(array,low,par-1,k);//向左递归找k,范围从low->par-1
}
public static int partation(int[] a,int low,int high){
// 将数组的首元素作为每一轮比较的基准
int tmp=a[low];
while(low<high){
while(low<high&&a[high]<=tmp){
high--;
}
a[low]=a[high];
while (low<high&&a[low]>=tmp){
low--;
}
a[high]=a[low];
}
a[low]=tmp;
return low;
}
}