题目描述
blablabla
样例
blablabla
算法1
(暴力枚举) $O(n^2)$
blablabla
时间复杂度
python 代码
def bsearch_first(data, k):
l, r = 0, len(data)-1
while l < r:
mid = l + r >> 1
if data[mid] >= k:
r = mid
else:
l = mid + 1
if data[l] != k: # 不存在,返回-1
return -1
return l
def bsearch_last(data, k):
l, r = 0, len(data)-1
while l < r:
mid = l + r + 1 >> 1
if data[mid] <= k:
l = mid
else:
r = mid - 1
if data[l] != k: # 不存在,返回-1
return -1
return l
if __name__ == '__main__':
n, m = map(int, input().split())
data = list(map(int, input().split()))
while m:
x = int(input())
first = bsearch_first(data, x)
last = bsearch_last(data, x)
print(first, last)
m -= 1
还是y总的用时能更少,这种为-1的时候会判定2次
有没有可能两个search函数之中只有一个返回-1?