微信公众号:路人zhang
扫码关注微信公众号

回复“面试手册”,获取本站PDF版

回复“简历”,获取高质量简历模板

回复“加群”,加入程序员交流群

回复“电子书”,获取程序员类电子书

当前位置: 算法 > 剑指offer > 剑指offer 40. 最小的k个数

题目描述

输入整数数组 arr ,找出其中最小的 k 个数。例如,输入4、5、1、6、2、7、3、8这8个数字,则最小的4个数字是1、2、3、4。

示例 1:

输入:arr = [3,2,1], k = 2
输出:[1,2] 或者 [2,1]

示例 2:

输入:arr = [0,1,2,1], k = 1
输出:[0]

限制:

  • 0 <= k <= arr.length <= 10000
  • 0 <= arr[i] <= 10000

题解

(堆) O(n)

使用大根堆存储 k 个最小的数,怎么存呢,遍历每个数,先加到大根堆中,如果堆的大小大于 k 则弹出一个堆顶,所以数都遍历完后,此时堆中存的就是最小的 k 个数。

时间复杂度

O(n)

空间复杂度

O(n)

C++ 代码

class Solution {
public:
    vector<int> getLeastNumbers(vector<int>& arr, int k) {
        priority_queue<int> heap;
        for (auto x : arr) {
            heap.push(x);
            if (heap.size() > k)
                heap.pop();
        }
        vector<int> res;
        while (heap.size()) {
            res.push_back(heap.top());
            heap.pop();
        }
        return res;
    }
};

Java 代码

class Solution {
    public int[] getLeastNumbers(int[] arr, int k) {
        PriorityQueue<Integer> heap = new PriorityQueue<>((a, b) -> b - a);
        for (int x : arr) {
            heap.offer(x);
            if (heap.size() > k)
                heap.poll();
        }
        int[] res = new int[k];
        int index = 0;
        while (!heap.isEmpty()) {
            res[index ++ ] = heap.poll();
        }
        return res;
    }
}

Python 代码

class Solution:
    def getLeastNumbers(self, arr: List[int], k: int) -> List[int]:
        heap = []
        for x in arr:
            heapq.heappush(heap, x)
        
        res = []
        for _ in range(k):
            res.append(heapq.heappop(heap))
        
        return res

本文由读者提供Github地址:https://github.com/tonngw


点击面试手册,获取本站面试手册PDF完整版