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

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

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

import java.util.*;

public class Main {

public Main() {
}

public boolean getMinK(int n, Integer[] pInputArray, int k, Integer[] pOutputArray) {
    if (k > n) return false;
    PriorityQueue<Integer> pq = new PriorityQueue<>(k, new Comparator<Integer>(){
        public int compare(Integer o1, Integer o2) {
            return o2 - o1;
        }
    });
    for (Integer i : pInputArray) {
        if (pq.size() == k && i < pq.peek()) {
            pq.poll();
        }
        if (pq.size() < k) {
            pq.offer(i);
        }
    }
    for (int i = k - 1; i >= 0; i--) {
        pOutputArray[i] = pq.poll();
    }
    return true;
}

public static void main(String[] args) {
    Main solution = new Main();
    Scanner in = new Scanner(System.in);
    while (in.hasNextInt()) {
        int n = in.nextInt(), k = in.nextInt();
        Integer[] pInputArray = new Integer[n];
        Integer[] pOutputArray = new Integer[k];
        for (int i = 0; i < n; i++) {
            pInputArray[i] = in.nextInt();
        }
        boolean res = solution.getMinK(n, pInputArray, k, pOutputArray);
        if (res) {
            for (Integer i : pOutputArray) {
                System.out.print(i + " ");
            }
            System.out.println();
        }
    }
} 

}

我居南半坡 文章被收录于专栏

多刷题,积蓄力量,欢迎讨论

全部评论

相关推荐

ddd7_:跟我一模一样,加微信的hr都同一个,扫码了白年书人查看图片
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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