LeetCode 面试题 17.14. 最小K个数

思路

题目地址:https://leetcode-cn.com/problems/smallest-k-lcci/
思路:最小堆的简单应用

代码

public class Solution {

    public int[] smallestK(int[] arr, int k) {
        int[] result = new int[k];
        PriorityQueue<Integer> heap = new PriorityQueue<>();
        for (Integer num : arr) {
            heap.add(num);
        }
        int num = 0;
        while (num < k) {
            result[num] = heap.poll();
            num++;
        }
        return result;
    }

}

你可能感兴趣的:(LeetCode)