2018-06-15 LeetCode35

题目描述

给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
你可以假设数组中无重复元素。
示例 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

我的解法

由于数组已有序,所以直接进行搜索,不过感觉对于开头和结尾的处理有点繁琐。

class Solution:
    def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        if target <= nums[0]:
            return 0
        for pos in range(len(nums)-1):
            if target > nums[pos] and target < nums[pos+1]:
                return pos+1
            elif target == nums[pos]:
                return pos
        if target > nums[-1]:
            return len(nums)
        elif target == nums[-1]:
            return len(nums)-1

最优解法

从数组两端同时向中间逼近。

class Solution:
    def searchInsert(self, nums, target):
        if not nums:
            return 0
        i = 0
        j = len(nums) - 1
        if j == 0:
            return 0 if nums[j] >= target else j + 1

        binaryIndex = (j - i + 1) // 2
        while i < j - 1:
            if nums[binaryIndex] < target:
                i = binaryIndex
            if nums[binaryIndex] > target:
                j = binaryIndex
            if target == nums[binaryIndex]:
                return binaryIndex
            binaryIndex = (j + i) // 2

        if target <= nums[i]:
            return i
        elif target <= nums[j]:
            return j
        else:
            return j + 1

你可能感兴趣的:(2018-06-15 LeetCode35)