LeetCode题库第三十五题(简单系列)

题目及要求:

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

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

示例 1:

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

这个题目还是比较简单的,但是提交的时候还是错了一次,因为没有考虑到target<nums[0]的情况,所以挂了

第一版本:

class Solution:
    def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        if target in nums:
            return nums.index(target)
        else:
            for i in nums:
                if target>i:
                    n=nums.index(i)
                    nums.insert(n+1,target)
                    break
            return nums.index(target)

报错如下:

终极通过版

class Solution:
    def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        if target in nums:
            return nums.index(target)
        else:
            if target<nums[0]:
                nums.insert(0, target)
            for i in nums[::-1]:
                if target>i:
                    n=nums.index(i)
                    nums.insert(n+1,target)
                    break
            return nums.index(target)

然后惯例给个图片~

再放个执行用时分布图表,其实可以看出还是可以继续优化的。

猜你喜欢

转载自blog.csdn.net/nodoself/article/details/82180975