搜索插入位置

2024-04-27 02:42:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我在解决一个问题(leetcode35)。对于测试用例,我的代码返回null 输入:[1,3,5,6],7。找不到窃听器。在

给定已排序数组和目标值,如果找到目标,则返回索引。如果不是,则返回按顺序插入的索引。在

可以假定数组中没有重复项。在

Example 1:

Input: [1,3,5,6], 5
Output: 2
Example 2:

Input: [1,3,5,6], 2
Output: 1
Example 3:

Input: [1,3,5,6], 7
Output: 4
Example 4:

Input: [1,3,5,6], 0
Output: 0

低于我的代码。我知道这个问题有很多不同的解决方案,我的解决方案不是最优的。但是请你帮我弄清楚错误在哪里,而不是给出一个全新的解决方案。谢谢!在

^{pr2}$

Tags: 代码目标inputoutput排序顺序example错误
3条回答

第一部分是正确的,使用list.index并捕获异常。但是你的第二部分(没有指纹)

  for i in range(len(nums)):
      if nums[i] - target > 0:
          return i  # return if True
      else: 
          return len(nums)  # return if False

这意味着无论发生什么,for循环的第一次迭代都将始终返回。在

您需要将else块从for循环中取出;如下所示:

^{pr2}$

看看这个!在

class Solution:
    def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        nums.append(target)         
        nums.sort()                 
        for i,j in enumerate(nums): 
            if target == j:         
                return i            

for循环中的if-else错误,应将else放在for循环之外。在

class Solution(object):
    def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        try:
            return nums.index(target)
        except:
            for i in range(len(nums)):
                print i
                if nums[i] - target > 0:
                    return i

            print "hello", len(nums)
            return len(nums)

但是,bisect已经包含了您需要的所有内容。在

^{pr2}$

作为练习,您可以尝试再次执行此练习,而不使用索引,您可能需要使用enumerate和if-else条件。在

相关问题 更多 >