python - 搜索插入位置

标签 python

我正在解决一个问题(leetcode 35)。我的代码为测试用例返回 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

在我的代码下面。我知道这个问题有很多不同的解决方案,我的解决方案不是最优的。但请帮助我了解错误在哪里,而不是提供全新的解决方案。谢谢!

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
                else: 
                    print "hello", len(nums)
                    return len(nums)

最佳答案

您的第一部分是正确的,使用 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 block 移出 for 循环;像这样:

def searchInsert(self, nums, target):
    try:
        return nums.index(target)
    except IndexError:  # best to use explicit except
        for index, value in enumerate(nums):  # more pythonic than range(len(nums))
             if value > target:
                  return index
        return len(nums)

关于python - 搜索插入位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54007783/

相关文章:

python - python中方便的时间字符串解析

python - 在for循环中获取下一个变量

python - 通过 iter_messages 识别相册和图像

python - SqlAlchemy 将方括号放在 sql server 2014 表名上

python - 检测4个有趣的像素

python - 在 Eclipse 中为项目的每个脚本设置运行配置

Python:遍历字典中的字典

python - 无法从网页的某些脚本标记中获取电子邮件链接

python - 在 django-admin 中使用 django 将用户数据导出为 CSV

python - 后分布 Pystan 的最高密度区间 (HDI)