题目
思路
二分查找
代码
class Solution:
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if target < nums[0]: return 0
if target > nums[-1]: return len(nums)
left = 0; right = len(nums) - 1
position = -1
while left <= right:
mid = (left + right) // 2
if nums[mid] < target:
left = mid + 1
elif nums[mid] > target:
position = mid
right = mid - 1
else:
return mid
return position