题目描述
参考:
https://blog.csdn.net/WJPnb1/article/details/126360962?spm=1001.2014.3001.5502
寻找第一个大于等于x的,即最后时刻l1及左边都小于x,r1及右边都大于x。
更新时,nums[mid]小于x时
将l1 更新为mid–>nums[l1]<mid满足上述要求
while l1+1!=r1:
mid = (l1+r1)//2
if nums[mid]<x:
l1 = mid
else:
r1 = mid
寻找最后一个大于等于x的,最后时刻l2及左边都小于等于x,r2及右边都大于x。
更新时,当nums[mid]>x时,将r2更新为mid,即是使nums[r2]>x
while l2+1!=r2:
mid = (l2+r2)//2
if nums[mid]>x:
r2 = mid
else:
l2 = mid
Python代码
N = 100010
nums = [0 for _ in range(N)]
if __name__ == '__main__':
n,q = map(int,input().split())
nums[:n] = list(map(int,input().split()))
for i in range(q):
x = int(input())
l1,r1 = -1,n
l2,r2 = -1,n
while l1+1!=r1:
mid = (l1+r1)//2
if nums[mid]<x:
l1 = mid
else:
r1 = mid
if nums[r1] != x:
print(-1,-1)
continue
while l2+1!=r2:
mid = (l2+r2)//2
if nums[mid]>x:
r2 = mid
else:
l2 = mid
if nums[l2] == x:
print(r1,l2)
else:
print(r1,r2)