二分查找
Problem
Solution 1
class BinarySearch:
def getPos(self, A, n, val):
val_pos = -1
left = 0
right = n-1
now_pos = (left + right)//2
while 1:
if A[now_pos] < val: # 当前值 < val,
if val == A[now_pos+1]: # 右边第一个 = val
val_pos = now_pos + 1 # 更新val_pos
break # 跳出
left = now_pos
now_pos = (left + right)//2
else: # A[now_pos] >= val # 当前值 = val,仍要「向左查找」,确保找到「第一次出现的位置」
right = now_pos
now_pos = (left + right)//2
if left==right-1: # 范围缩小到两个数
if val==A[left]:
val_pos = left # 优先输出左边
elif val==A[right]:
val_pos = right
break # 即使左右都不符合也要break
return(val_pos)Solution 2
Last updated