您的位置:首页 > 其它

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

2019-07-08 13:23 120 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/A994850014/article/details/95054998

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

Day8:搜索插入位置

一. 问题背景:

二. 解决思路:

二分查找:

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

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

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

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

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

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

三. 算法实现:

[code]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题目:

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/

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: