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.