35搜索插入位置

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

你可以假设数组中无重复元素。

示例 1:

输入: [1,3,5,6], 5
输出: 2

示例 2:

输入: [1,3,5,6], 2
输出: 1

示例 3:

输入: [1,3,5,6], 7
输出: 4

示例 4:

输入: [1,3,5,6], 0
输出: 0

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/search-insert-position 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

Solution 1

二分搜索变体
执行用时:48 ms
内存消耗:14.1 MB

class Solution:
    def searchInsert(self, nums: [int], target: int) -> int:
        if nums == []:
            nums.append(target)
            return 0
        head = 0
        tail = len(nums)-1
        # 找开始位置
        while(1):
            mid = int((head+tail+1)/2)
            if nums[mid] == target:
                return mid
            # 优先考虑target在前半段
            if nums[head] <= target and target <= nums[mid-1]:
                tail = mid-1
            elif nums[mid] <= target and target <= nums[tail]:
                head = mid
            elif target < nums[head]:
                nums.insert(head, target)
                return head
            elif nums[tail] < target:
                nums.insert(tail+1, target)
                return tail+1
            else:  # nums[mid-1] < target < nums[mid]
                nums.insert(mid, target)
                return mid