快排思想求topk问题
public static void main(String[] args) {
// int[] nums = new int[]{5, 3, 2, 10, 8, 1, 4, 9, 3, 12};
int[] nums = new int[]{5, 3, 2, 7, 8, 1, 4, 9, 6, 10};
int top = 2;
int topk = topk(nums, 0, nums.length -1, top - 1);
System.out.print("\t" + topk);
}
public static int topk(int[] nums, int start, int end, int k) {
int target = nums[start];
int i = start; //不能+1,否则会直接跳过比较
int j = end;
while (i < j) {
while (i < j && nums[j] >= target) j--; // 因为target是从左开始,所以此处应该从右开始,确保i>j不会出现
while (i < j && nums[i] <= target) i++;
if (i < j) swap(nums, i, j);
}
swap(nums, start, i);
if (i < k) return topk(nums, i + 1, end, k);
else if (i > k) return topk(nums, start, i - 1, k);
else return nums[i];
}
public static void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}