To reorder the array so that all the positive elements are on their position, that is, the first element is 1, the second is 2, and so on so forth. Then the first element which A[i]!=i+1 is the one should return.
class Solution {
public:
int firstMissingPositive(int A[], int n) {
for (int i=0; i<n; i++) {
while (A[i]!=i+1) {
if (A[i]<=0 || A[i]>n || A[i]==A[A[i]-1]) break;
int temp=A[i];
A[i]=A[temp-1];
A[temp-1]=temp;
}
}
for (int i=0; i<n; i++) {
if (A[i]!=i+1){
return i+1;
}
}
return n+1;
}
};