/**
* 寻找Top k 大
*
* @param nums
* @param k
* @return
*/
public static int findKthLargest(int[] nums, int k) {
return findKthLargest(nums, k, 0, nums.length - 1);
}
// 快速排序-选择的内部实现
public static int findKthLargest(int[] nums, int k, int left, int right) {
if (left == right) return nums[left];
int pIndex = (right + left) / 2;
int pivot = nums[pIndex];
//swap(nums, pIndex, right);
int i = left;
int j = right - 1;
while (true) {
while (nums[i] < pivot && i < right) i++;
while (j > left && nums[j] > pivot) j--;
if (i < j) {
swap(nums, i, j);
i++;
j--;
} else break;
}
swap(nums, i, right);
// 这时pivot被放在i的位置,i是第数组中第i+1大的位置
int target = nums.length - k;
if (i == target) return pivot;
else if (i > target) return findKthLargest(nums, k, left, i - 1);
else return findKthLargest(nums, k, i + 1, right);
}
另外一种方法
import java.util.*;
public class GetTopK {
public static void main(String[] args) {
int[] arr = {5, 2, 4, 6, 8, 3};
ArrayList<Integer> list = GetLeastNumbers(arr, 3);
System.out.println(list.toString());
}
/**
* @param input
* @param k
* @return
*/
public static ArrayList<Integer> GetLeastNumbers(int[] input, int k) {
ArrayList<Integer> res = new ArrayList();
if (k == 0 || k > input.length) return res;
int l = 0, r = input.length;
while (l < r) {
int p = partition(input, l, r);
if (p + 1 == k) {
ArrayList<Integer> temp = new ArrayList();
for (int i = 0; i < k; i++) temp.add(input[i]);
return temp;
}
if (p + 1 < k) l = p + 1;
else r = p;
}
return res;
}
/**
* @param input
* @param l
* @param r
* @return
*/
private static Integer partition(int[] input, int l, int r) {
int pivot = input[r - 1];
int i = l;
for (int j = l; j < r - 1; j++) {
// 这一步判断确定选出最大的k个数还是最小的k个数
if (input[j] > pivot) {
swap(input, i, j);
i++;
}
}
swap(input, i, r - 1);
return i;
}
/**
* @param arr
* @param i
* @param j
*/
private static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}