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.
思路:
将A[i]移到A[A[i]]的位置,(O(n)时间,就地实现),再扫描一遍,当A[i]!=i的时候,表明缺失i。
特殊情况:i从1->n-1的时候,A[i]=i。此时视A[0]的情况而定。
代码:
int firstMissingPositive(int A[], int n) {
if(n == 0 || A == NULL)
{
return 1;
}
for(int i=0; i<n; )
{
if(A[i]>=0 && A[i]<n && A[i]!=i && A[i]!=A[A[i]])
{
int t=A[i];
A[i]=A[t];
A[t]=t;
continue;
}
else
{
++i;
}
}
int j;
for(j=1; j<n; ++j)
{
if(A[j]!=j)
{
return j;
}
}
if(A[0] == n)
{
return n+1;
}
else
{
return n;
}
}