Question
Given an unsorted integer array, find the first missing positive integer.
For example,
Given [1,2,0] return 3,
and [3,4,-1,1] return 2.
Your algorithm should run in O(n) time and uses constant space.
Hide Tags Array
Hide Similar Problems (M) Missing Number
Solution
Get idea from here.
class Solution(object):
def firstMissingPositive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if nums==None or len(nums)==0:
return 1
i = 0
while i<len(nums):
if nums[i]<=len(nums) and nums[i]>0 and nums[nums[i]-1]!=nums[i]:
j = nums[i] - 1
nums[i], nums[j] = nums[j], nums[i]
i -= 1
i += 1
for i in range(len(nums)):
if nums[i]!=(i+1):
return i+1
return len(nums)+1