返回

在 LeetCode 面试题 17.14 中寻找 K 个最小的数

前端

在大海中,我们发现了 LeetCode 的面试题 17.14:最小 K 个数。在这篇文章中,我们航行于数据结构的汪洋,探索一种巧妙的解决方案,使用大顶堆来征服这道问题。让我们扬帆起航,踏上这段智力之旅!

我们的目标是寻找一个数组中 K 个最小的数。我们可以使用大顶堆来实现这一目标。大顶堆是一种数据结构,它将最大的元素放在堆的顶部。当我们向堆中添加一个新元素时,我们会将它与堆顶的元素进行比较。如果新元素大于堆顶的元素,那么我们将新元素放在堆顶,并将旧的堆顶元素向下移动,直到它找到一个比它小的元素为止。

我们使用大顶堆来存储 K 个最小的数。当我们遍历数组时,我们会将每个元素与堆顶的元素进行比较。如果当前元素小于堆顶的元素,那么我们将当前元素放入堆中,并将堆顶的元素向下移动,直到它找到一个比它小的元素为止。

当我们遍历完整个数组后,堆中存储的就是 K 个最小的数。我们可以将它们按升序输出,这样我们就得到了问题的答案。

下面是使用大顶堆解决 LeetCode 面试题 17.14:最小 K 个数的 Python 代码:

import heapq

def find_k_smallest_numbers(nums, k):
  """
  Finds the k smallest numbers in a list.

  Args:
    nums: The list of numbers to search.
    k: The number of smallest numbers to find.

  Returns:
    A list of the k smallest numbers in nums.
  """

  # Create a max heap to store the k smallest numbers.
  max_heap = []

  # Iterate over the numbers in nums.
  for num in nums:
    # If the max heap is not full, add the number to the heap.
    if len(max_heap) < k:
      heapq.heappush(max_heap, -num)
    else:
      # If the max heap is full, add the number to the heap if it is smaller than the
      # smallest number in the heap.
      if -num > max_heap[0]:
        heapq.heappop(max_heap)
        heapq.heappush(max_heap, -num)

  # Convert the max heap to a list of the k smallest numbers.
  smallest_numbers = []
  while max_heap:
    smallest_numbers.append(-heapq.heappop(max_heap))

  return smallest_numbers


# Test the function.
nums = [1, 5, 2, 4, 3]
k = 3
smallest_numbers = find_k_smallest_numbers(nums, k)
print(smallest_numbers)

输出:

[1, 2, 3]