【堆】leetcode每日一题—面试题 17.14. 最小K个数

题目:
设计一个算法,找出数组中最小的k个数。以任意顺序返回这k个数均可。
【堆】leetcode每日一题—面试题 17.14. 最小K个数_第1张图片
解答:

class Solution:
    def smallestK(self, arr: List[int], k: int) -> List[int]:
        if k == 0:
            return list()

        hp = [-x for x in arr[:k]]
        heapq.heapify(hp)
        for i in range(k, len(arr)):
            if -hp[0] > arr[i]:
                heapq.heappop(hp)
                heapq.heappush(hp, -arr[i])
        ans = [-x for x in hp]
        return ans

你可能感兴趣的:(leetcode,Python,leetcode,算法,面试)