
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
left = 0
right = len(nums) - 1
while left <= right:
mid = left + ((right - left)>>1)
if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid + 1
else:
right = mid -1
# 与普通二分查找的区别是,如果目标值不存在于数组中,
# 返回它将会被按顺序插入的位置。
# 这里如果目标值不存在于数组中,则插入的位置为left
return left
这个博客主要介绍了如何使用二分查找算法在已排序的列表中搜索目标值,并返回目标值的索引。如果目标值不存在,算法会返回其在列表中应该被插入的位置,以保持列表的有序性。内容涉及二分查找的基本逻辑和Python实现。
443

被折叠的 条评论
为什么被折叠?



