https://leetcode-cn.com/problems/zui-xiao-de-kge-shu-lcof

基于堆排序

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import heapq
class Solution:
    def getLeastNumbers(self, arr: List[int], k: int) -> List[int]:
        if k == 0:
            return []

        # Init
        hp = [-i for i in arr[:k]]
        heapq.heapify(hp)

        # Traverse
        for i in range(k, len(arr)):
            if -hp[0] > arr[i]:
                heapq.heappop(hp)
                heapq.heappush(hp, -arr[i])

        return [-x for x in hp]

基于快速排序

1