分治法求解第k大/小元素:
public int findKthLargest(int[] nums, int k) {
if (nums == null || nums.length == 0) {
return 0;
}
//将第K个最大元素转换为第l个最小元素
int l = nums.length + 1 - k;
return findKthLargestWithIndex(nums, 0, nums.length - 1, l);
}
public static int findKthLargestWithIndex(int[] nums, int left, int right, int l) {
int element = 0;
int p = randomPartitionEx(nums, left, right);
if (p - left + 1 == l) {
element = nums[p];
}
if (p - left + 1 > l) {
element = findKthLargestWithIndex(nums, left, p, l);
}
if (p - left + 1 < l) {
element = findKthLargestWithIndex(nums, p + 1, right, l - (p - left + 1));
}
return element;
}
//随机化划分
public static int randomPartitionEx(int[] a, int left, int right) {
int r = new Random().nextInt(right - left + 1) + left; //生成一个随机数,即是主元所在位置
swap(a, right, r); //将主元与序列最右边元素互换位置,这样就变成了之前快排的形式。
return partition(a, left, right); //直接调用之前的代码
}
//确定主元后进行比较交换数据
public static int partition(int[] a, int low, int high) {
int i = low;
int j = high;
int base = a[low];
while (i != j) {
while (a[j] >= base && i < j) {
j--;
}
while (a[i] <= base && i < j) {
i++;
}
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
//将a[low] a[i]的值进行交换,因为a[i]始终是比base小的数的最右边的一个数
a[low] = a[i];
a[i] = base;
return i;
}
//交换数组a中的a[i]和a[j]
private static void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}