Day8:搜索插入位置(二分查找)

leetcode地址:https://leetcode-cn.com/problems/search-insert-position/submissions/

Day8:搜索插入位置

一. 问题背景:

二. 解决思路:

二分查找:

    二分查找也被称为折半查找,是在一个有序数组中查找特定元素位置的查找算法。二分查找要求查找序列采用顺序存储,且按关键字有序排列。

        1. 从中间元素开始搜索。如果正好是要搜索元素,则搜索结束。

        2. 如果不等,则在大于或者小于要搜索元素的那一半执行二分查找。

        3. 如果在某一步后要查找的数组为空,则代表找不到。

    这种算法每一次比较都使搜索范围缩小一半,因此非常高效。

    注:1. 在求mid时可能发生溢出;2. 常数步的前进。 

三. 算法实现:

def search(data, item):
    left, right = 0, len(data) - 1
    
    while left <= right:
        middle = (left + right) // 2
        
        if item < data[middle]:
            right = middle - 1
        elif item > data[middle]:
            left = middle + 1
        else:
            return middle
            
    return left

firstSearch = search([1, 3, 5, 8, 11], 11)
print(firstSearch)
secondSearch = search([2, 3, 4, 8, 10], 5)
print(secondSearch)

注:其他二分查找相关leetcode题目:

扫描二维码关注公众号,回复: 11500378 查看本文章

1. x 的平方根    https://leetcode-cn.com/problems/sqrtx/

2. 搜索二维矩阵    https://leetcode-cn.com/problems/search-a-2d-matrix/

3. 搜索旋转排序数组    https://leetcode-cn.com/problems/search-in-rotated-sorted-array/

4. 搜索旋转排序数组 II    https://leetcode-cn.com/problems/search-in-rotated-sorted-array-ii/

猜你喜欢

转载自blog.csdn.net/A994850014/article/details/95054998