35、Search Insert Position

Given a sorted array 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 may assume no duplicates in the array.

Example:

Input: [1,3,5,6], 5
Output: 2

Solution - Python:

#!/usr/bin/env python
# -*- coding = utf-8 -*-

""" @ Create Time: 2018/04/30 @ Author: songpo.zhang @ Target: """

def searchInsert(nums, target):
    left, right = 0, len(nums)-1
    while left <= right:
        mid = int((left + right) / 2)
        if target == nums[mid]:
            return mid
        elif target > nums[mid]:
            left = mid + 1
        else:
            right = mid -1
        return left

if __name__ == "__main__":
    print(searchInsert([1, 3, 5, 6], 5))