35. Search Insert Position

 

Promble

Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You must write an algorithm with O(log n) runtime complexity.

Input: nums = [1,3,5,6], target = 5
Output: 2
Input: nums = [1,3,5,6], target = 2
Output: 1
Input: nums = [1,3,5,6], target = 7
Output: 4

Approach

  1. 判断target是否在nums中,如果在,返回位置
  2. 如果不在,则判断插入的位置,使用二分查找
    1. 定义左右边界,lo, hi = 0, len(nums)
    2. 判断lo<hi的情况
    3. 计算中位 mid=(lo+hi) // 2
    4. 移动左右边界
      1. 左边界: if nums[mid] < target: lo = mid+1
      2. 有边界:if nums[mid] > target: hi = mid
    5. 返回左边界,极为需要插入的位置

Code

class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:

        if target in nums:
            return nums.index(target)
        else:
            lo, hi = 0, len(nums)
            while lo < hi:
                mid = (lo+hi) // 2
                if nums[mid] < target:
                    lo = mid+1
                else:
                    hi = mid 
            return lo