美文网首页
LeetCode 35. Search Insert Posit

LeetCode 35. Search Insert Posit

作者: singed | 来源:发表于2018-08-20 21:22 被阅读0次

链接

https://leetcode-cn.com/problems/search-insert-position/description/

要求

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

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

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

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

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

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

相关代码

class Solution(object):
    def searchInsert(self, nums, target):
        if target in nums:
            return nums.index(target)
        else:
            nums.append(target)
            return sorted(nums).index(target)

心得体会

与其寻找可以插入target的位置,不如append到nums后返回target所在位置更简单效率也更高。

相关文章

网友评论

      本文标题:LeetCode 35. Search Insert Posit

      本文链接:https://www.haomeiwen.com/subject/znlriftx.html