Leetcode 面试题 17.14.最小K个数(Smallest K LCCI)

Leetcode 面试题 17.14.最小K个数

1 题目描述(Leetcode题目链接)

  设计一个算法,找出数组中最小的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))

2 题解

  堆排序,更多关于堆。

class Solution:
    def smallestK(self, arr: List[int], k: int) -> List[int]:
        heap_size = len(arr)
        def min_heapify(i):
            l = 2*i + 1
            r = 2*i + 2
            if l < heap_size and arr[l] < arr[i]:
                smallest = l
            else:
                smallest = i
            if r < heap_size and arr[r] < arr[smallest]:
                smallest = r
            if smallest != i:
                arr[i], arr[smallest] = arr[smallest], arr[i]
                min_heapify(smallest)
        for i in range(heap_size//2 - 1, -1, -1):
            min_heapify(i)
        retv = []
        for i in range(k):
            retv.append(arr[0])
            arr[0] = arr[heap_size - 1]
            heap_size -= 1
            min_heapify(0)
        return retv

不如直接调库。

class Solution:
    def smallestK(self, arr: List[int], k: int) -> List[int]:
        return heapq.nsmallest(k, arr)
class Solution:
    def smallestK(self, arr: List[int], k: int) -> List[int]:
        return sorted(arr)[:k]

你可能感兴趣的:(Leetcode)