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


全部评论

相关推荐

不愿透露姓名的神秘牛友
今天 13:47
点赞 评论 收藏
分享
每晚夜里独自颤抖:这个在牛客不是老熟人了吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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