Here is the problem, any advice about code improvement, more efficient implementation in terms of time complexity, functional bugs, etc. are appreciated.
Given an unsorted integer array, find the first missing positive integer.
For example,
Given[1,2,0]
return3
,
and[3,4,-1,1]
return2
.Your algorithm should run in O(n) time and use constant space.
def firstMissingPositive(nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 1
for i,v in enumerate(nums):
if v > len(nums):
nums[i]=-1
elif v <= 0:
nums[i]=-1
else:
while i+1 != nums[i] and 0<nums[i]<=len(nums):
#print i, nums[i]-1, nums[i], nums[nums[i]-1]
v = nums[i]
nums[i] = nums[v-1]
nums[v-1] = v
#nums[i], nums[nums[i]-1] = nums[nums[i]-1], nums[i]
if nums[i] > len(nums) or nums[i] <=0:
nums[i] = -1
for i,v in enumerate(nums):
if nums[i] != i+1:
return i+1
return len(nums)+1
if __name__ == "__main__":
print firstMissingPositive([1,2,0])
print firstMissingPositive([3,4,-1,1])
[4, 5, 7, 8]
return, 6 or 1? \$\endgroup\$n
comparisons for eachn-1
in the list. \$\endgroup\$