提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
二分法常见问题
—本文主要聚焦,如何解决这些问题,
提示:以下是本篇文章正文内容,下面案例可供参考
一、二分法的前提和本质
进入的二分法必须满足如下的前提
二分法指针移动的本质
二、开始逐个问题解答
1.解答疑问1/3/4
2.解答疑问2
最后一个问题:mid =Value要不要单独判断?
解答:还是看目的,如果序列里面的值不重复,且只要找到这个值得位置就可以结束程序,则可以增加mid =Value一个单独判断,帮助快速结束判断
3.标题对应的目标场景和Python代码
目标1:寻找小于5的最大数字
list_int = [1, 2, 3, 4, 5, 5, 5, 7, 8, 9]
find_num = 5
def search_tree(list_int, find_num):
left = 0
right = len(list_int)
while left + 1 < right:
mid = (left + right) // 2
if list_int[mid] >= find_num:
right = mid
else:
left = mid
return list_int[left]
result = search_tree(list_int, find_num)
print(result)
目标2:寻找等于5的第一个数字的索引
list_int = [1, 2, 3, 4, 5, 5, 5, 7, 8, 9]
find_num = 5
def search_tree(list_int, find_num):
left = 0
right = len(list_int)
while left + 1 < right:
mid = (left + right) // 2
if list_int[mid] >= find_num:
right = mid
else:
left = mid
return right #列表中有多个5,这里返回结果的索引
result = search_tree(list_int, find_num)
print(result)
目标3:寻找等于5的最后一个数字的索引
list_int = [1, 2, 3, 4, 5, 5, 5, 7, 8, 9]
find_num = 5
def search_tree(list_int, find_num):
left = 0
right = len(list_int)
while left + 1 < right:
mid = (left + right) // 2
if list_int[mid] <= find_num:
left = mid
else:
right = mid
return left #列表中有多个5,这里返回结果的索引
result = search_tree(list_int, find_num)
print(result)
目标3:寻找大于5的最小数字
list_int = [1, 2, 3, 4, 5, 5, 5, 7, 8, 9]
find_num = 5
def search_tree(list_int, find_num):
left = 0
right = len(list_int)
while left + 1 < right:
mid = (left + right) // 2
if list_int[mid] <= find_num:
left = mid
else:
right = mid
return list_int[right]
result = search_tree(list_int, find_num)
print(result)