我正在解决一个问题(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/