题解 | #输入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 + " "));
        }
    }
}


全部评论

相关推荐

这不纯纯作弊了吗😢😢😢
编程界菜鸡:信这个的这辈子有了,这智商你靠啥都没用
点赞 评论 收藏
分享
头顶尖尖的程序员:我也是面了三四次才放平心态的。准备好自我介绍,不一定要背熟,可以记事本写下来读。全程控制语速,所有问题都先思考几秒,不要急着答,不要打断面试官说话。
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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