Skip to content

Fix outdate number error of findRepeatNumber #281

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 5, 2020

Conversation

tczhangzhi
Copy link
Contributor

原方法忘记在交换后更新当前i指针对应的num,导致测试用例 nums = [1, 3, 4, 0, 2, 5, 3] 返回1(应该返回3):

from typing import List

def findRepeatNumber(nums: List[int]) -> int:
    for i, num in enumerate(nums):
        while i != num:
            if num == nums[num]:
                return num
            nums[i], nums[num] = nums[num], nums[i]
           # 原方法缺少这一行:
           # num = nums[i]
    return -1

nums = [1, 3, 4, 0, 2, 5, 3]
findRepeatNumber(nums)

因此,本次提交作出了修正:

def findRepeatNumber(nums: List[int]) -> int:
    for i, num in enumerate(nums):
        while i != num:
            if num == nums[num]:
                return num
            nums[i], nums[num] = nums[num], nums[i]
            num = nums[i]
    return -1

修正后可通过三种边界测试和其他笔者想到的任何符合题目要求情况:

nums = [1, 3, 4, 0, 2, 5, 3] # should return 3
nums = [2, 4, 1, 0, 2, 5, 3] # should return 2
nums = [2, 4, 1, 0, 6, 5, 3] # should return -1
findRepeatNumber(nums)

另,虽然复杂度相同,但读者更偏爱只使用一个循环表示该过程:

def findRepeatNumber(nums: List[int]) -> int:
    i = 0
    while i < len(nums):
        print(nums)
        if nums[i] == i:
            i += 1
            continue
        if nums[nums[i]] == nums[i]: return nums[i]
        nums[nums[i]], nums[i] = nums[i], nums[nums[i]]
    return -1

nums = [1, 3, 4, 0, 2, 5, 3]
findRepeatNumber(nums)

@yanglbme yanglbme merged commit 1e5ece4 into doocs:master Aug 5, 2020
@tczhangzhi tczhangzhi deleted the patch-1 branch August 5, 2020 02:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants