题目:
解决方法:快排、堆
1.快排
public class Solution {
public int findKth(int[] a, int n, int K) {
// write code here
quickSort(a,0,a.length-1,K-1);
return a[K-1];
}
public static void quickSort(int[] a,int low,int high,int k){
if(low>high)
return;
int i = low;
int j = high;
int temp = a[low];
while(i<j){
while(temp>=a[j]&&i<j)
j--;
while(temp<=a[i]&&i<j)
i++;
if(i<j){
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
a[low] = a[j];
a[j] = temp;
if(j==k)
return ;
if(j>k)
quickSort(a,low,j-1,k);
else
quickSort(a,j+1,high,k);
}
2.堆
public int findKth(int[] a, int n, int K) {
// write code here
PriorityQueue<Integer> pq = new PriorityQueue<>();
for(int i =0;i<a.length;i++){
pq.add(a[i]);
if(pq.size()>K)
pq.poll();
}
return pq.poll();
}