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.
class Solution {
public:
int firstMissingPositive(int A[], int n) {
for(int ii = 0; ii < n; ii ++) {
// Use while to make number on position ii to be ii + 1 or invalid number.
// And swap may be called more than one time.
while(A[ii] != ii + 1 && A[ii] >= 1 && A[ii] <= n && A[ii] != A[A[ii] - 1])
swap(A[ii], A[A[ii] - 1]);
}
int ii = 0;
for(; ii < n; ii ++) {
if(A[ii] != ii + 1) return ii + 1;
}
return n + 1;
}
};