确定性就直接查找输出,没有则输出-1。
list=[]
x=0
for x in range(1,101):
list.append(x)
a=len(list)
print(list)
def chazhao(a,s,t,x):
while(s<=t):
mid=int((s+t)/2)
if(x<a[mid]):
t=mid-1
elif(x>a[mid]):
s=mid+1
else:
return mid+1
return -1
print(chazhao(list,1,100,36))
随机性查找可以先将数组进行重新排序再进行查找。
class Solution:
def search(self, nums: List[int], target: int) -> int:
nums.sort() #排序
found = False #标记是否查找到了
i = 0
index =0
while i < len(nums) and nums[i] <= target and not found: #在比target小的元素里查找
if nums[i] == target:
found = True
index = i
i += 1
if not found:
return -1
else:
return index