题目来自牛客网
https://www.nowcoder.com/practice/097ab63cffa847d89716f2ca8c23524f?tpId=90&tqId=30914&tPage=7&rp=7&ru=/ta/2018test&qru=/ta/2018test/question-ranking
两种方法,方法一:使用快排,经过一轮之后,元素temp被放到中间,前面的小于等于它,后面的大于等于它,如果元素temp的位置是i(从0开始),那么temp为第i+1小的数,本题求第k大的数,所以i=len-k(在代码中对应int k = len - scanner.nextInt();),len为数组中元素个数。如果temp的位置小于i,那么,往后找,如果大于i,往前找,相等,temp即为所求。
方法二:求第k大数,使用小顶堆,堆中有k个元素,堆顶元素为当前的第k大数,如果堆中不足k个元素,直接入堆,否则,如果大于堆顶,删除堆顶,这个数入堆。最后,堆顶元素即为所求。
代码如下:
import java.util.*;
public class Solution139 {
//使用小顶堆
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] strs = scanner.nextLine().split(" ");
int len = strs.length;
int[] num = new int[len];
for (int i = 0; i < len; i++) {
num[i] = Integer.parseInt(strs[i]);
}
int k = scanner.nextInt();
scanner.close();
//PriorityQueue是用堆实现的,默认就是小顶堆
PriorityQueue<Integer> queue = new PriorityQueue<>(k);
for (int i = 0; i < len; i++) {
if (queue.size() < k) {
queue.offer(num[i]);
} else if (num[i] > queue.peek()) {
queue.poll();
queue.offer(num[i]);
}
}
System.out.println(queue.peek());
}
//使用快排的思想
public static void main2(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] strs = scanner.nextLine().split(" ");
int len = strs.length;
int[] num = new int[len];
for (int i = 0; i < len; i++) {
num[i] = Integer.parseInt(strs[i]);
}
int k = len - scanner.nextInt();
scanner.close();
int begin = 0;
int end = len - 1;
int index = aTurnQuickSort(num, begin, end);
while (index != k) {
if (index < k) {
begin = index + 1;
index = aTurnQuickSort(num, begin, end);
} else {
end = index - 1;
index = aTurnQuickSort(num, begin, end);
}
}
System.out.println(num[index]);
}
public static int aTurnQuickSort(int[] num, int begin, int end) {
int i = begin;
int j = end;
int temp = num[i];
while (i < j) {
while (i < j && num[j] >= temp) {
j--;
}
num[i] = num[j];
while (i < j && num[i] <= temp) {
i++;
}
num[j] = num[i];
}
num[i] = temp;
return i;
}
}