Leetcode刷题100天—面试题 17.14. 最小K个数(优先队列)—day27

系统管理员 2022-09-12 03:57 191阅读 0赞

前言:

作者:神的孩子在歌唱

大家好,我叫运智

image-20210903184512357

面试题 17.14. 最小K个数

难度中等128收藏分享切换为英文接收动态反馈

设计一个算法,找出数组中最小的k个数。以任意顺序返回这k个数均可。

示例:

  1. 输入: arr = [1,3,5,7,2,4,6,8], k = 4
  2. 输出: [1,2,3,4]

提示:

  • 0 <= len(arr) <= 100000
  • 0 <= k <= min(100000, len(arr))

    package 优先队列;

    import java.util.PriorityQueue;

    / https://leetcode-cn.com/problems/smallest-k-lcci/ */
    public class 面试题17_14最小K个数 {
    // 将数组里的整数存入优先队列,在poll输出前k个数

    1. public int[] smallestK(int[] arr, int k) {

    // 定义返回数组

    1. int[] res=new int[k];

    // 定义优先队列

    1. PriorityQueue<Integer> queue=new PriorityQueue<>();//默认小顶堆

    // for循环遍历存入队列

    1. for(int ar:arr) {
    2. queue.add(ar);
    3. }

    // 在通过for循环遍历

    1. for(int i=0;i<k;i++) {
    2. res[i]=queue.poll();
    3. }
    4. return res;
    5. }

    }

本人csdn博客:https://blog.csdn.net/weixin\_46654114

转载说明:跟我说明,务必注明来源,附带本人博客连接。

发表评论

表情:
评论列表 (有 0 条评论,191人围观)

还没有评论,来说两句吧...

相关阅读