簡體   English   中英

交換數組中的元素導致問題

[英]swap elements in an array causing issue

新年快樂。 我有一個關於在 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]))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM