class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
for i in range(len(nums)):
if nums[i] == target: # equal
return i
elif i < len(nums)-1 and target > nums[i] and target < nums[i+1] : #target In the middle
return i+1
elif i == 0 and target < nums[i]: # start
return i
return len(nums) # Does not exist in array
Just apply the dichotomy directly , That is, continue to use dichotomy approximation to find the first greater than or equal to \textit{target}target The subscript .
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
l,r = 0,len(nums)-1
while l <= r:
mid = (l+r)//2
if target == nums[mid]:
return mid
elif target < nums[mid]:
r = mid - 1
else:
l = mid +1
return l
nums = [1, 3, 5, 6]
target = 7
S = Solution()
result = S.searchInsert(nums,target)
print(result)