题解 | #输入n个整数,输出其中最小的k个#

输入n个整数,输出其中最小的k个

https://www.nowcoder.com/practice/69ef2267aafd4d52b250a272fd27052c

维护一个容量为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 + " "));
        }
    }
}


全部评论

相关推荐

点赞 评论 收藏
分享
皮格吉:不,有的厂子面试无手撕,可以试试。都是一边学一边面。哪有真正准备好的时候,别放弃
无实习如何秋招上岸
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务