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:
int firstMissingPositive(int A[], int n) {
if(n==0)
return 1;
int pos = 0;
while(pos<n)
{
if(A[pos]>=0&&A[pos]<n&&A[pos]!=A[A[pos]])
{
swap(A[A[pos]],A[pos]);
}
else
pos++;
}
for(int i=1;i<n;i++)
{
if(A[i]!=i)
return i;
}
return A[0]==n?n+1:n;
}
No comments:
Post a Comment