二分查找万能模板-python

由九章算法-令狐提出

data = [1,3,6,8,8,12,88,943]
# 第一个等于target的索引位置
def binarySearch(nums,target):
    if not nums:
        return -1
    start, end = 0, len(nums)-1
    while start + 1 < end:
        mid = start + (end-start)//2        
        if nums[mid] == target:
            end = mid
        elif nums[mid] < target:
            start = mid
        else:
            end = mid
    if nums[start] == target:
        return start
    if nums[end] == target:
        return end
binarySearch(data, 8)
data = [1,3,6,8,8,12,88,943]
# 最后一个等于target的索引位置
def binarySearch(nums,target):
    if not nums:
        return -1
    start, end = 0, len(nums)-1
    while start + 1 < end:
        mid = start + (end-start)//2        
        if nums[mid] == target:
            start = mid
        elif nums[mid] < target:
            start = mid
        else:
            end = mid
    if nums[start] == target:
        return start
    if nums[end] == target:
        return end
binarySearch(data, 8)

 

posted @ 2022-07-21 09:36  今夜无风  阅读(98)  评论(0编辑  收藏  举报