题目描述
输入 n 个不超过 10⁹ 的单调不减的(就是后面的数字不小于前面的数字)非负整数 a1,a2,…,an,然后进行 m 次询问。对于每次询问,给出一个整数 q,要求输出这个数字在序列中第一次出现的编号,如果没有找到的话输出 −1。
输入格式
第一行 2 个整数 n 和 m,表示数字个数和询问次数。
第二行 n 个整数,表示这些待查询的数字。
第三行 m 个整数,表示询问这些数字的编号,从 1 开始编号。
输出格式
输出一行,m 个整数,以空格隔开,表示答案。
输入输出样例
输入 #1
11 3 1 3 3 3 5 7 9 11 13 15 15 1 3 6
输出 #1
1 2 -1
说明/提示
数据保证,1≤n≤10⁶,0≤aᵢ,q≤10⁹,1≤m≤10⁵
本题输入输出量较大,请使用较快的 IO 方式。
方法一: ( 二分查找 )
a,b = map(int,input().split())
lst0 = list(map(int,input().split()))
lst1 = list(map(int,input().split()))
# print(a,b)
# print(lst0)
# print(lst1)
def BinarySearch(key):
low = 0
high = len(lst0)-1
mid = 0
count = -1
while low <= high:
mid = (low + high) // 2
if key == lst0[mid]:
count = mid+1
if key <= lst0[mid]:
high = mid-1
else:
low = mid+1
return count
for i in range(b):
x = lst1[i]
print(BinarySearch(x),end=' ')
方法二: ( 使用 bisect 库 )
import bisect
a,b = map(int,input().split())
lst0 = list(map(int,input().split()))
lst1 = list(map(int,input().split()))
#由于bisect找不到数据不返回-1,而是返回合适的插入位置,所以自定义search函数
def search(x): # x为待找数据
k = bisect.bisect_left(lst0,x) # k为x合适的插入位置(索引)
if k >= len(lst0): # 索引大于列表总长度
return -1
elif x != lst0[k]: # 待找数据不在列表中
return -1
return k+1
for i in range(b):
print(search(lst1[i]),end=' ')