Commit 8dd4f546 by BellCodeEditor

auto save

parent adaf6f8a
Showing with 57 additions and 8 deletions
# 什么都没有输出,说明不在列表里
bingo_num = 20 # 要查找的数:20
num_list = [1, 3, 5, 8, 11, 15, 17, 18, 20, 21]
low = 0
high = len(num_list)-1
while low <= high:
mid = (low + high) // 2
guess_num = num_list[mid]
if guess_num == bingo_num:
print('找到了,他在列表里的索引是:',mid)
break
elif guess_num < bingo_num:
low = mid + 1
else:
high = mid - 1
import random
alist = []
for i in range(1,101):
alist.append(i)
num = random.choice(alist)
def search(alist,num):
low = 0
high = len(alist)-1
while low <= high:
mid = (low + high) // 2
guess_num = alist[mid]
if guess_num == num:
return mid
elif guess_num < num:
low = mid + 1
else:
high = mid - 1
return None
result = search(alist,num)
print('需要猜测的数字是:',num)
print('猜测数字所在的索引是:',result)
\ No newline at end of file
import random
一、问题抽象化:这道题的要求是要找到哪个target?还是要找到第一个比target小(或小于等于)的元素?
还是第一个比target大(或大于等于)的元素?
alist = []
for i in range(1, 101):
alist.append(i)
num = random.choice(alist)
# 请完善二分查找函数binary_search(),查找出num在列表alist里面的索引位置
def binary_search(alist,num):
\ No newline at end of file
二、如果当前mid指向的值等于target了之后,我应该怎么处理?是直接return?还是移动left或者right
三、最后一次循环的时候(循环是以left <= right作为判断条件),left === right,那么这个时候,我
是移动left还是移动right,移动之后,是left指向的我想返回的结果,还是right
四、没找到怎么办?
给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target
写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment