目錄
預備知識:
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;
}
}