【发布时间】:2020-12-24 03:38:00
【问题描述】:
我一直在研究一个二分搜索问题。
不是将一个键编号与给定列表匹配,而是要求我将键列表(列表 B)与另一个列表(列表 A)匹配。如果键与列表 A 中的数字匹配,则输出应返回 A 中存在该数字的第一个索引。如果列表 A 中不存在键号,则返回 -1
假设列表 A 和列表 B 是:
A = [1, 5, 8, 12, 13]
B = [8, 1, 23, 1, 11]
由于两个列表中都存在 8,因此输出为 2,因为列表 A 中的 8 在 [2] 处。使用这个逻辑,最终的整体输出应该变成:
matched_list = [2, 0, -1, 0, -1]
下面是我的代码。如果您还可以在行内找到任何逻辑错误,将不胜感激,但是,我最关心的是运行时间。当我在计算机上按 Enter 键时,需要很长时间才能处理,并且软件(我使用 VS Code)最终崩溃了。
我有 16GB RAM 和 Intel Core i7,所以拖累它的不应该是设备,而是算法。
def binary_search(A, B, n):
# We match the numbers in key list, B, to the numbers in A
low, high = 0, n-1
# low limit is initialised to A[0], the first number of list A
# high limit initialised to the last number of the list, A[n-1]
matched_list = []
for i in B:
middle = (high+low)//2
while low <= high:
if i > A[middle]:
low = middle+1
elif i < A[middle]:
high = middle-1
else:
matched_list.append(middle)
if low > high:
return(-1)
return(matched_list)
A = [1, 5, 8, 12, 13]
B = [8, 1, 23, 1, 11]
n = 5 # this is the length of list A
print(binary_search(A, B, n))
有没有办法改进我的算法?
【问题讨论】:
标签: python algorithm binary-search