题解 | #寻找第K大#
寻找第K大
http://www.nowcoder.com/practice/e016ad9b7f0b45048c58a9f27ba618bf
记录
import java.util.*;
public class Solution {
Random random = new Random();
public int findKth(int[] a, int n, int K) {
// write code here
int l = 0;
int r = n - 1;
int target = n - K;
while (true){
int index = partition(a, l, r);
if (index == target){
return a[index];
} else if (index < target){
l = index + 1;
} else {
r = index - 1;
}
}
}
public int partition(int[] a, int l, int r){
//if (r > l){
//int index = l + 1 + random.nextInt(r - l);
//swap(a, l ,index);
// }
int privot = a[l];
int i = l + 1;
int j = r;
while (true){
while ( i < r && a[i] < privot){
i++;
}
while ( j > l && a[j] > privot){
j--;
}
if (i >= j){
break;
}
swap(a, i ,j);
}
swap(a, j, l);
return j;
}
public void swap(int[] a, int i, int j){
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
查看23道真题和解析