📅  最后修改于: 2023-12-03 15:10:21.790000             🧑  作者: Mango
给定一个整数数组,找到数组中最近的一对数对,使得其中一个数是另一个数的倍数。例如,对于数组 [3,5,8,10,12,15],答案是 (5,10),它们是数组中最接近的一对数对,并且 5 是 10 的倍数。
def closest_multiple_pair(array):
array = sorted(array)
min_diff = float('inf')
closest_pair = None
for i in range(len(array) - 1):
for j in range(i + 1, len(array)):
if array[j] % array[i] == 0:
diff = array[j] - array[i]
if diff < min_diff:
min_diff = diff
closest_pair = (array[i], array[j])
return closest_pair
>>> closest_multiple_pair([3,5,8,10,12,15])
(5, 10)
>>> closest_multiple_pair([1,2,3,4,5])
(2, 4)
>>> closest_multiple_pair([1,2,8])
(2, 8)
>>> closest_multiple_pair([4,6,10,14])
(6, 10)
>>> closest_multiple_pair([1,3,5])
None
以上是 Python 实现,你可以根据自己熟悉的编程语言来实现这个算法。