Leetcode35-搜索插入位置
思路:二分法,注意特殊情况的判断,当target大于所有数时,插入到列表末尾。
代码:
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
left = 0
right = len(nums) - 1
if target > nums[-1]:
return len(nums)
while left < right:
mid = (left + right) // 2
if nums[mid] < target:
left = mid + 1
elif nums[mid] >= target:
right = mid
return right