该题与左闭右闭二分查找的区别
二分查找的while条件里是否判断nums[mid] == target 决定了left < right or left <= right
如果有 if nums[mid] == target: return True 则left <= right
若无 则 left < right
在while 条件为 left < right的情况下时,right = len(nums)
且right指针实际nums的长度 (在边界插入时,right取len(nums)-1会出现插入不到超出列表范围的情况(因为取len(nums)时,是判断数组内第一个比target大的元素,有可能并没有这个元素,而插入到数组范围外),如果判断数组内有无target就无需取right = len(nums)而取right = len(nums)-1)
代码:
class Solution:
def searchInsert(self, nums, target: int) -> int:
n = len(nums)
left = 0
right = n
while left < right:
mid = left + (right - left)//2
if nums[mid] < target:
left = mid + 1
else:
right = mid
return left
class Solution:
def searchInsert(self, nums, target: int) -> int:
n = len(nums)
left = 0
right = n - 1 #若为n-1时,需要最后判断一下边界值
while left < right:
mid = left + (right - left)//2
if nums[mid] < target:
left = mid + 1
else:
right = mid
return left if nums[left] >=target else left+1