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.
Using something like Bitmap
class Solution {
public:
int firstMissingPositive(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int * pos = new int[n];
size_t i;
memset(pos, 0, sizeof(int)*n);
for(i=0; i<n; i++)
if(A[i] > 0 && A[i] <= n)
pos[A[i]-1] = 1;
for(i=0; i<n; i++)
if(pos[i] == 0)
break;
return i+1;
}
};