Leetcode刷题100天—面试题 17.14. 最小K个数(优先队列)—day27
前言:
作者:神的孩子在歌唱
大家好,我叫运智
面试题 17.14. 最小K个数
难度中等128收藏分享切换为英文接收动态反馈
设计一个算法,找出数组中最小的k个数。以任意顺序返回这k个数均可。
示例:
输入: arr = [1,3,5,7,2,4,6,8], k = 4
输出: [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个数public int[] smallestK(int[] arr, int k) {
// 定义返回数组
int[] res=new int[k];
// 定义优先队列
PriorityQueue<Integer> queue=new PriorityQueue<>();//默认小顶堆
// for循环遍历存入队列
for(int ar:arr) {
queue.add(ar);
}
// 在通过for循环遍历
for(int i=0;i<k;i++) {
res[i]=queue.poll();
}
return res;
}
}
本人csdn博客:https://blog.csdn.net/weixin\_46654114
转载说明:跟我说明,务必注明来源,附带本人博客连接。
还没有评论,来说两句吧...