题目链接:https://leetcode-cn.com/problems/search-insert-position/
难度:简单

描述:
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
请必须使用时间复杂度为35. 搜索插入位置 - 图1的算法。

提示:
数组长度:[1, 10000]

题解

  1. class Solution:
  2. def searchInsert(self, nums: List[int], target: int) -> int:
  3. left, right = 0, len(nums) - 1
  4. while left <= right:
  5. mid = (left + right) // 2
  6. if nums[mid] < target:
  7. left = mid + 1
  8. elif nums[mid] > target:
  9. right = mid - 1
  10. else:
  11. return mid
  12. return left