对于 LeetCode 上的二和问题,它说:
给定一个整数数组 nums 和一个整数目标,返回两个数字的索引,使它们相加等于目标。 您可以假设每个输入都有一个解决方案,并且您不能两次使用相同的元素。 您可以按任意顺序返回答案。
Input: nums = [2,7,11,15], target = 9
Input: nums = [3,2,4], target = 6
Input: nums = [3,3], target = 6
所有三个问题的输出都是:
[0,1]
[1,2]
[0,1]
但由于某种原因,我的代码未能通过最后一个测试用例并打印出:
[0,1]
[1,2]
[]
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
temp = 0
tempValue = 0
for x in nums: # x is 3
temp = target - x # temp is 3
for y in nums: # y is 3
if nums.index(x) != nums.index(y):
tempValue = x + y # 3+3 = 6
if tempValue == target:
return [nums.index(x), nums.index(y)]
最佳答案
您的代码行为不符合预期的原因是 num.index(x)
返回列表中匹配元素的 first 索引。因此,如果列表中有重复的元素(如第三种情况),语句 if nums.index(x) != nums.index(y):
将永远不会返回 True
.
关于python - 为什么大小为 2 的列表不适用于此嵌套 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72573490/