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数组中对应的位置。
class Solution {
public:
int firstMissingPositive(int A[], int n) {
int i=0;
while(i<n)
{
if(A[i]>=0&&A[i]<n&&A[i]!=A[A[i]])
{
int t=A[i];
A[i]=A[A[i]];
A[t]=t;
}
else i++;
}
for(i=1;i<n;i++)
{
if(A[i]!=i) return i;
}
return A[0]==n?n+1:n;
}
};