Problem Statement
(Source) 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.
Analysis
The idea is to traverse through the whole array and put elements into their correct position in corresponding sorted array
. Then another scan would find the first missing positive integer.
Solution
class Solution(object):
def firstMissingPositive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 1
n = len(nums)
for index in xrange(n):
num = nums[index]
while num != index + 1:
if 1 <= num <= n and nums[num - 1] != num:
nums[num - 1], nums[index] = nums[index], nums[num - 1]
num = nums[index]
else:
break
for index in xrange(n):
if nums[index] != index + 1:
return index + 1
return nums[-1] + 1