【Python】LeetCode算法_二分查找

35. 搜索插入位置

给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。假设数组中无重复元素。
如:输入:[1,3,5,6], 2 ,输出:1

def searchInsert(nums, target):
    """搜索插入位置"""
    low = 0
    high = len(nums)
    if target <= nums[low]:
        return low
    if target > nums[high-1]:
        return high
    while low < high:
        mid = low + (high - low)//2
        if target < nums[mid]:
            high = mid
        elif target > nums[mid]:
            low = mid +1
        else:
            return mid
    return low

nums_1 = [1,3,5,6]
print searchInsert(nums_1, 2)

猜你喜欢

转载自blog.csdn.net/Treasure99/article/details/85080454
今日推荐