【发布时间】:2021-12-05 23:22:23
【问题描述】:
我最近在一次采访中遇到了这个问题,但一直无法解决。给定一个排序列表:
li = [1,2,2,3,4,4,4,4,5,5,5...]
返回与目标匹配的所有元素的索引ex. 4,时间复杂度为 O(log n)。
这个问题的设置告诉我这是一个二分搜索问题。我用类似下面的东西回答了这个问题,但还没有找到更好的答案:
data = [2,3,5,6,8,9,12,12,12,14,17,19,22,25,27,28,33,37]
target = 12
def binary_search(data, target):
low = 0
high = len(data) - 1
while low <= high:
mid = (high + low) // 2
if data[mid] == target:
return mid
elif data[mid] > target:
high = mid - 1
else:
low = mid + 1
return False
def return_other_indices(data, target, match_index):
output = [match_index]
i = match_index + 1
while data[i] == target:
output.append(i)
i += 1
i = match_index - 1
while data[i] == target:
output.append(i)
i -= 1
return output
match_index = binary_search(data, target)
output = return_other_indices(data, target, match_index)
print(output)
有更好的方法吗?
【问题讨论】:
-
您可以使用
bisect模块吗? -
请定义“更好”
-
@Jab 理想情况下完全不使用第二个函数,或者至少不使用两个 while 循环。
标签: python binary-search