题目描述
寻找N个数字中最大的K个数字
package chapter_2_binary;
import java.util.Random;
import java.util.Scanner;
/**
* @author LiangGe
*
* 寻找一批数字中最K大数
*
* 使用方法类似快速排序查找
*
*/
public class question_2_5_1 {
private static Random random = new Random(47);
public static void swap(int[] data, int i, int j) {
int tmp = data[i];
data[i] = data[j];
data[j] = tmp;
}
/**
* @param data
* @param start
* @param end
* @return
*
* 随机版本的划分法
*
*/
public static int partition(int[] data, int start, int end) {
// 每次随机查收划分基准的位置,并与末尾元素交换
int shift = random.nextInt(end - start + 1);
int p = start + shift;
swap(data, p, end);
int tmp = data[end];
// 此处容易出现,i误以为每次都是-1
int i = start - 1;
// j从start开始,误以为-1
for(int j=start; j<=end; j++) {
if(data[j] < tmp) {
i ++;
swap(data, j, i);
}
}
swap(data, i+1, end);
return i + 1;
}
public static int findKBigest(int[] data, int k, int start, int end) {
int partition = partition(data, start, end);
int tmp = end - partition;
// 前两个if出现的概率最大,放在前面,减少if的判断次数
if(k < tmp) {
return findKBigest(data, k, partition + 1, end);
} else if(k > (tmp + 1)) {
return findKBigest(data, k - (tmp + 1), start, partition - 1);
} else if(k == tmp) {
return partition + 1;
} else {
return partition;
}
}
/**
* @param data
* @param k
* @param start
* @param end
* @return
*
* 使用类似快速排序算法寻找前K大的数字
*
*/
public static int findKBig(int[] data, int k, int start, int end) {
if(k > data.length) {
return 0;
} else if(k < 0) {
return end + 1;
} else {
return findKBigest(data, k, start, end);
}
}
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
scanner.nextLine();
while(num -- > 0) {
int n = scanner.nextInt();
int k = scanner.nextInt();
scanner.nextLine();
String string = scanner.nextLine();
String[] strs = string.split(" ");
int[] data = new int[strs.length];
for(int i=0; i< data.length; i++) {
data[i] = Integer.parseInt(strs[i]);
}
int start = findKBig(data, k, 0, data.length-1);
for(int i=start; i< data.length; i++) {
System.out.printf("%3d", data[i]);
}
}
}
}