[英]How should I modify my code so that twosum function works?
The question is in Leetcode, which is:问题出在 Leetcode 中,它是:
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
给定一个整数数组 nums 和一个整数目标,返回两个数字的索引,使它们相加为目标。 Each input would have exactly one solution, and you may not use the same element twice.
每个输入将只有一个解决方案,并且您不能两次使用相同的元素。
Here is my code for this exercise.这是我用于此练习的代码。
def twoSum(nums: List[int], target: int) -> List[int]:
for i in range(len(nums)):
for j in range(1,len(nums)):
if nums[i]+nums[j]==target:
return i,j
return i,j
twoSum([8,3,7,9,2],9)
#Result: (0, 4)
The output is not correct as 8+2=10
( nums[0] + nums[4]
) not equal to 9.输出不正确,因为
8+2=10
( nums[0] + nums[4]
) 不等于 9。
Why does this happen?为什么会发生这种情况?
You have two issues with your code:您的代码有两个问题:
return
will just return at the end of the first iteration of the outer loop.return
将在外循环的第一次迭代结束时返回。 Since i is still at 0 and j is all the way up to len(nums) - 1
, you get (0, 4) as result.len(nums) - 1
,因此结果为 (0, 4) 。 Removing it should resolve this issue. A possible solution would look like this:一个可能的解决方案如下所示:
def twoSum(nums: List[int], target: int) -> List[int]:
for i in range(len(nums)):
for j in range(i+1, len(nums)):
if nums[i]+nums[j] == target:
return i,j
return -1, -1
The -1, -1 will only occur if there is no solution. -1, -1 只有在没有解决方案时才会出现。 Since it is stated in the question that there is always exactly one solution, this should never happen.
由于问题中指出始终只有一个解决方案,因此永远不会发生这种情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.