leetcode35. 搜索插入位置

187 阅读1分钟

35. 搜索插入位置

给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。数组中无重复元素。

示例 :

输入: [1,3,5,6], 2
输出: 1
class Solution(object):
    def searchInsert(self, nums, target):
        # :type nums: List[int]
        # :type target: int
        # :rtype: int
        left = 0
        right = len(nums)
        while left < right:  # 二分查找只适用顺序存储结构。
            mid = left + (right - left) // 2
            if nums[mid] > target:
                right = mid
            elif nums[mid] < target:
                left = mid + 1
            else:
                return mid
        return left