新年快乐。我有一个关于在 Python 环境下交换数组中的元素的问题。没有问题的代码是:
def findMissingNumber(nums):
length = len(nums)
result = []
i = 0
while i < length:
# num = nums[i]
target = nums[i] - 1
if nums[i] != i+1 and nums[i] != nums[target]:
# swap with the nums[i]-1
nums[target], nums[i]= nums[i], nums[target]
else:
i += 1
for j in range(length):
if nums[j] != j+1:
result.append(j+1)
return result
print(findMissingNumber([2, 3, 1, 8, 2, 3, 5, 1]))
print(findMissingNumber([2, 4, 1, 2]))
print(findMissingNumber([2, 3, 2, 1]))
有答案:
[4, 6, 7]
[3]
[4]
错误的是:
def findMissingNumber(nums):
length = len(nums)
result = []
i = 0
while i < length:
num = nums[i]
target = num - 1
if num != i+1 and num != nums[target]:
# swap with the num-1
nums[target], num = num, nums[target]
else:
i += 1
for j in range(length):
if nums[j] != j+1:
result.append(j+1)
return result
print(findMissingNumber([2, 3, 1, 8, 2, 3, 5, 1]))
print(findMissingNumber([2, 4, 1, 2]))
print(findMissingNumber([2, 3, 2, 1]))
有答案:
[4, 6, 7]
[3, 4]
[3, 4]
我不确定为什么参考(我应该称之为)引起麻烦。你介意详细解释一下。
谢谢。
带有注释的固定代码。
def findMissingNumber(nums):
length = len(nums)
result = []
i = 0
while i < length:
# num and nums[i] have the same value but doesnt refer to same memory location
num = nums[i]
target = num - 1
if num != i+1 and num != nums[target]:
# swap with the num-1
# incorrect swap, num value is not referencing the list index, but has a copy of its value,
# so instead of swapping value with num, do it from the list like below
# nums[target], num = num, nums[target]
# correct swap
nums[target], nums[i] = nums[i], nums[target]
else:
i += 1
for j in range(length):
if nums[j] != j+1:
result.append(j+1)
return result
print(findMissingNumber([2, 3, 1, 8, 2, 3, 5, 1]))
print(findMissingNumber([2, 4, 1, 2]))
print(findMissingNumber([2, 3, 2, 1]))
谢谢。你介意多谈谈 num 和 nums[i] 之间的区别吗?我仍然不太了解它。
@QiangSuper 当您
num = nums[i]
这样做时,您正在做的是nums[i]
取值,然后创建一个新变量并为其分配值。现在 num 和 nums[i] 是单独的引用。所以,无论你用 num 做什么都不会反映在nums[i]
,这就是为什么交换没有反映在nums
列表中。谢谢你的解释。是不是说python中的a = b是将b的值复制到a,但是不会在它们之间建立链接关系?
@QiangSuper,不,实际上 a = b,两者都将指向相同的位置,因为您正在引用整个变量。因此,在上述情况下,如果你已经建立
numbers = nums
,那么所作的任何更改上numbers
会反映nums
以及谢谢你的帮助。我试着总结你分享的结果。如果你给一个新变量赋值,比如 a = b[0]。a 是内存中的一个新位置,因此对 a 的任何更改都不会影响 b[0]。但是,如果您为整个变量分配一个新引用,例如 a = b,a 仍然指向 b 在内存中的位置,b 中的任何更改都会影响 b。我对么?我可以问为什么吗?欣赏。