维护一个容量为k的大根堆 当接收完所有数后 这个大根堆就存储了min K的数 最后将这些数升序输出
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextInt()) {
int n = in.nextInt();
int k = in.nextInt();
Queue<Integer> pq = new PriorityQueue<>(Comparator.reverseOrder());
while (n-- > 0) {
if (pq.size() == k) {
pq.offer(in.nextInt());
pq.poll();
} else {
pq.offer(in.nextInt());
}
}
pq.stream().sorted().forEach(x -> System.out.printf(x + " "));
}
}
}

京公网安备 11010502036488号