Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

Swap in an array in Python issues

I have a question about the swap in an array in Python, which causing repeating issues. The code with issues are:

def findFirstMissingPositive(nums):
    i = 0
    length = len(nums)
    while i < length:
        # for normal number, swap
        print(nums[i], i, nums)
        if 0 < nums[i] <= length and nums[i] != nums[nums[i]-1]:
            nums[i], nums[nums[i]-1] = nums[nums[i]-1], nums[i]
        # skip negative and larger number
        else:
            i += 1
    for j, value in enumerate(nums):
        if value != j+1 and j > 0:
            return j+1
    # all align, then return the next positive number out of range
    return length+1


print(findFirstMissingPositive([-3, 1, 5, 4, 2]))

returning:

1 1 [-3, 1, 5, 4, 2]
1 1 [-3, 1, 5, 4, 2]
1 1 [-3, 1, 5, 4, 2]
1 1 [-3, 1, 5, 4, 2]

It looks like the loop got stuck at index 1. Once I updated the code by adding index = nums[i]-1

def findFirstMissingPositive(nums):
    i = 0
    length = len(nums)
    while i < length:
        index = nums[i]-1
        # for normal number, swap
        print(nums[i], i, nums)
        if 0 < nums[i] <= length and nums[i] != nums[index]:
            nums[i], nums[index] = nums[index], nums[i]
        # skip negative and larger number
        else:
            i += 1
    for j, value in enumerate(nums):
        if value != j+1 and j > 0:
            return j+1
    # all align, then return the next positive number out of range
    return length+1


print(findFirstMissingPositive([-3, 1, 5, 4, 2]))

returning

-3 0 [-3, 1, 5, 4, 2]
1 1 [-3, 1, 5, 4, 2]
-3 1 [1, -3, 5, 4, 2]
5 2 [1, -3, 5, 4, 2]
2 2 [1, -3, 2, 4, 5]
-3 2 [1, 2, -3, 4, 5]
4 3 [1, 2, -3, 4, 5]
5 4 [1, 2, -3, 4, 5]
3

I am not sure why I need this reference, rather than directly calling the nums[i].
Thanks for your help.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...