题目描述(简单难度)
解题思路
- 考虑二分查找的边界问题,找不到时,left值的变化情况
python 代码
class Solution:
def searchInsert(self, nums, target: int) -> int:
left = 0
right = len(nums)-1
while left <= right:
mid = (left+right)//2
if nums[mid] == target:
return mid
if target < nums[mid]:
right = mid - 1
else:
left = mid + 1
return left
s = Solution()
res = s.searchInsert([1,3,5,6], 4)
print('.....',res)