找到最左的索引,>= num的索引
def find_left(arr, num):
l, r = 0, len(arr) - 1
ans = -1
while l <= r:
m = l + (r - l) // 2 # 使用整除來避免浮點數
if arr[m] >= num:
ans = m
r = m - 1
else:
l = m + 1
return ans
arr = [1, 2, 3, 7, 7, 8, 8, 9, 10]
num = 8
res = find_left(arr, num)
print(res) # 5
練習:
def find_left(arr, num):
l = 0
r = len(arr)
ans = -1
while l <= r:
m = l + (r - l) // 2 # 中點是m
if arr[m] >= num: # 如果中點大於要找的值,要繼續往左側找,因為是>=所以更新ans
ans = m
r = m - 1
else:
l = m + 1
return ans
arr = [1, 2, 5, 7, 7, 8, 8, 9, 10]
num = 8
res = find_left(arr, num)
print(res)