06 二分搜索--ing

 

找到最左的索引,>= 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)

 

posted @ 2024-06-06 21:00  o蹲蹲o  阅读(2)  评论(0编辑  收藏  举报