两和解决方案不起作用不确定出了什么问题,我该如何修复我的解决方案



我在做经典的二和问题:给定一个整数数组,返回两个数字的索引,使它们加起来成为一个特定的目标。

您可以假设每个输入只有一个解决方案,并且不能两次使用同一个元素。

这是我的代码,我不知道为什么不起作用:

class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]: 
for num in nums: 
result = []
x = target - num
if x in nums: 
result.append(nums.index(x)) 
result.append(nums.index(num))
if nums.index(x)!=nums.index(num):
return result 

您的代码很好,但您可以将其简化为

  • make是静态的,因为它不需要self
  • 返回时直接构建数组,无需在之前创建
  • 使用enumerate获取第一个数字的标记,这允许您从下一个标记开始查找下一个数字,因此无需检查它是否不相同,并直接在结果中使用
  • 返回未找到的空列表
@staticmethod
def twoSum(nums: List[int], target: int) -> List[int]:
for idx, num in enumerate(nums):
x = target - num
if x in nums[idx + 1:]:
return [idx, nums.index(x)]
return []
print(Solution.twoSum([1, 2, 3, 4, 5, 6, 7, 8, 9], 10))  # [0,8]
print(Solution.twoSum([1, 2, 3, 4, 5, 6, 7, 8, 9], 15))  # [5,8]
print(Solution.twoSum([1, 2, 3, 4, 5, 6, 7, 8, 9], 2))   # []

相关内容

最新更新