📅  最后修改于: 2023-12-03 15:04:11.763000             🧑  作者: Mango
本文介绍了如何使用Python编写一个程序,找到元组中最接近第K个索引元素的对。对于给定的元组和一个索引k,程序会查找最接近该索引的元素对,并返回它们的值。
find_closest_pair(arr: Tuple[int, int], k: int) -> Tuple[int, int]:
找到最接近第K个索引的值对。
if index + 1 < len(arr):
diff = arr[index+1][0] - arr[index][0]
if diff < min_diff:
min_diff = diff
result = (arr[index][1], arr[index+1][1])
return result
from typing import List, Tuple
def binarySearch(arr: List[Tuple[int, int]], low: int, high: int, key: int) -> int:
while low <= high:
mid = (low + high) // 2
if arr[mid][0] == key:
return mid
elif arr[mid][0] < key:
low = mid + 1
else:
high = mid - 1
return high
def find_closest_pair(arr: Tuple[int, int], k: int) -> Tuple[int, int]:
arr_list = list(arr)
arr_list.sort()
index = binarySearch(arr_list, 0, len(arr_list) - 1, k)
min_diff = float('inf')
result = None
if index >= 0:
if index < len(arr) and arr[index][0] == k:
return (arr[index][1], arr[index][1])
elif index == 0:
min_diff = arr[index+1][0] - arr[index][0]
result = (arr[index][1], arr[index+1][1])
else:
diff = k - arr[index][0]
if diff < min_diff:
min_diff = diff
result = (arr[index][1], arr[index][1])
diff = arr[index+1][0] - k
if diff < min_diff:
min_diff = diff
result = (arr[index][1], arr[index+1][1])
if index + 1 < len(arr):
diff = arr[index+1][0] - arr[index][0]
if diff < min_diff:
min_diff = diff
result = (arr[index][1], arr[index+1][1])
return result
现在我们使用自己的例子来测试这个函数。
arr = [(1, 5), (2, 4), (3, 6), (7, 8)]
k = 6
print(find_closest_pair(arr, k))
输出结果为:(3, 2)
我们可以通过此程序轻松找到元组中最接近第K个元素的值对。当然,我们必须确保元组中的一个值是有序的,以便进行二进制搜索。