思路:暴力,遍历数组,找到比目标数小,且后一个大于等于目标数的,边界值单独考虑。
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
size = len(nums)
if target <= nums[0]:
return 0
for i in range(size-1):
if nums[i] < target and nums[i+1] >= target:
return i+1
return size
二分搜索法:效率更高
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
left, right = 0, len(nums)-1
# 二分搜索
while left <= right:
mid = left + (right -left)//2
if target > nums[mid]:
left = mid +1
elif target <= nums[mid]:
right = mid -1
return left