215. Kth Largest Element in an Array
The recursive tree of this problem looks like binary search tree.
public class Solution {
private int sort(int[] a, int lo, int hi, int k) {
int p = partition(a, lo, hi);
if (k == p) {
return a[p];
} else if (k < p) {
return sort(a, lo, p - 1, k);
} else {
return sort(a, p + 1, hi, k);
}
}
// This is an in-place implementation of partition in Algorithm (4th Edition)
private int partition(int[] a, int lo, int hi) {
int i = lo;
int j = hi + 1;
int v = a[lo];
while (true) {
while (i < hi && a[++i] < v) {}
while (j > lo && a[--j] > v) {}
if (i >= j) {
break;
}
exch(a, i, j);
}
exch(a, lo, j);
return j;
}
// Exchanges the elements in a[i] and a[j]
private void exch(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
// Fisher–Yates shuffle algorithm
private void shuffle(int[] a) {
Random random = new Random();
for (int i = a.length - 1; i >= 0; i--) {
// 0 <= r <= i
int r = random.nextInt(i + 1);
exch(a, i, r);
}
}
// If we sort the array in ascending order,
// the kth element of an array will be the kth smallest element.
// To find the kth largest element, we can pass k = length(Array) – k.
public int findKthLargest(int[] a, int k) {
shuffle(a);
return sort(a, 0, a.length - 1, a.length - k);
}
}