First Missing Positive
Given an unsorted integer array, find the first missing positive integer.
For example,
Given
and
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.
Solution: hash-table solution (intuitive approach, O(n) in time and space...)
The following code satisfies the constant space requirement. The key idea is: the first missed positive integer must in [1, n+1]. If we swap the integers and make sure and A[i] = i, we can easily check that which integer is missed.
Revised it at 2013-09-23:
Comments
Post a Comment