返回

乘法表中第k小的数 : 二分 + 计数判定 经典应用题

后端

在数学中,乘法表是一个将两个数字相乘的结果排列成表格的形式。乘法表在算术运算和数学教育中非常有用。

在计算机科学中,乘法表可以用作查找表来快速计算两个数字的乘积。乘法表也可以用来解决一些数学问题,比如求解线性方程组和多项式方程。

在LeetCode上,有一个问题叫做“乘法表中第k小的数”。这个问题要求我们找到一个正整数k,使得乘法表中第k小的数等于k。

这个问题可以用二分搜索和计数判定算法来解决。二分搜索是一种可以在有序数组中快速找到特定元素的算法。计数判定算法是一种可以快速计算一个数组中满足某个条件的元素数量的算法。

具体来说,我们可以先将乘法表中的所有数字从小到大排序,然后使用二分搜索来找到第k小的数字。在二分搜索过程中,我们可以使用计数判定算法来计算乘法表中小于或等于当前数字的数字数量。如果这个数量等于k,那么当前数字就是第k小的数字。否则,如果这个数量小于k,那么我们需要继续在数组的后半部分进行二分搜索。如果这个数量大于k,那么我们需要在数组的前半部分进行二分搜索。

使用这种方法,我们可以快速找到乘法表中第k小的数字。这种方法的时间复杂度是O(log(n * n)),其中n是乘法表中数字的数量。

下面是一个Python实现的示例代码:

def kth_smallest_in_multiplication_table(n, k):
  """
  Finds the kth smallest number in the multiplication table of size n x n.

  Args:
    n: The size of the multiplication table.
    k: The index of the kth smallest number.

  Returns:
    The kth smallest number in the multiplication table.
  """

  # Create a list of all the numbers in the multiplication table.
  numbers = []
  for i in range(1, n + 1):
    for j in range(1, n + 1):
      numbers.append(i * j)

  # Sort the numbers in ascending order.
  numbers.sort()

  # Use binary search to find the kth smallest number.
  low = 0
  high = len(numbers) - 1
  while low <= high:
    mid = (low + high) // 2
    # Count the number of numbers in the list that are less than or equal to the
    # middle number.
    count = 0
    for number in numbers:
      if number <= numbers[mid]:
        count += 1

    # If the count is equal to k, then the middle number is the kth smallest
    # number.
    if count == k:
      return numbers[mid]

    # If the count is less than k, then the kth smallest number is in the
    # second half of the list.
    elif count < k:
      low = mid + 1

    # If the count is greater than k, then the kth smallest number is in the
    # first half of the list.
    else:
      high = mid - 1

  # Return the kth smallest number.
  return numbers[k]


if __name__ == "__main__":
  n = 3
  k = 5
  print(kth_smallest_in_multiplication_table(n, k))

这个代码的时间复杂度是O(log(n * n)),其中n是乘法表中数字的数量。