当前位置: 移动技术网 > IT编程>脚本编程>Python > 【leetcode 简单】第十一题 搜索插入位置

【leetcode 简单】第十一题 搜索插入位置

2018年08月08日  | 移动技术网IT编程  | 我要评论

原阳县,3xiao77,漫客

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

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

示例 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
        """

        index=-1
        last=0
        try:
            return nums.index(target)
        except:
            for i in range(len(nums)):
                if target > nums[i]:
                    last+=1
        nums.insert(last,target)
        return index if index > 1 else last

 



如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网