题解 | #输入n个整数,输出其中最小的k个#
输入n个整数,输出其中最小的k个
http://www.nowcoder.com/practice/69ef2267aafd4d52b250a272fd27052c
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
//最大的k个->小根堆,最小的k个->大根堆
PriorityQueue<Integer> pq = new PriorityQueue<>((x, y) -> (y - x));
while (in.hasNextInt()) {
int n = in.nextInt(), k = in.nextInt();
int[] nums = new int[n];
//用数组承接输入整数
for (int i = 0; i < n; i++) {
nums[i] = in.nextInt();
}
//利用大根堆特性将最小的k个存入
for(int num : nums){
if(pq.size() == k && pq.peek() > num) pq.poll();
if(pq.size() < k) pq.offer(num);
}
//用数组将大根堆中的元素倒序存入
int[] res = new int[pq.size()];
for(int i = res.length - 1; i >= 0; i--) res[i] = pq.poll();
//从小到大输出
for(int i = 0; i < k; i++){
if(i == k - 1) System.out.print(res[i]);
else System.out.print(res[i] + " ");
}
}
}
}