之前写二分查找特定值觉得很简单,所以今天面试官让我写个二分查找区间的算法,时间复杂度0(logn)时,我想这还不简单。结果写了十五分钟,盯着又臭又长的代码还在那里纠结边界条件。回头上网查找没有找到满意的文章,于是自己又尝试了一下。但是代码还是太长,如果大家有看到更好的解法,还请踢我一下!
data = list(map(int, input().split())) #输入一串单调不减数字,以空格隔开
target = int(input()) #期望返回data中值为target的区间端点
def search(data, target, start, end):
if (end < start) or (data[start] > target) or (data[end] < target): #data中不存在target
return [-1, -1]
if end == start: #只有一个值,判断是否为target
left = right = end if data[end] == target else -1
return [left, right]
index = (end+start)//2
if data[index] < target:
return search(data, target, index+1, end) #index要+1避免死循环
elif data[index] > target:
return search(data, target, start, index-1) #index要-1作为end终点
else:
left = (index+start)//2 #相加除2相比start+偏移值,更加简洁
right = (end+index)//2
while left > start:
if data[left] == target:
left = (start+left)//2
elif data[left] < target:
tem = left
left += (left-start)//2
start = tem
while data[left] < target: #left最终应该为区间左端点,或者左端点-1的位置
left += 1
while right < end: #右端点类似操作
if data[right] == target:
right = (right+end+1)//2 #加1避免死循环
elif data[right] > target:
tem = right
right -= (end-right)//2
end = tem
while data[right] > target:
right -= 1
return [left, right]
left, right = search(data, target, 0, len(data)-1)
print(f'{left} {right}')