class Solution {
//first must figure out what is the exactly meaning of this problem
//second hash table is the key
//should practice more
public:
int firstMissingPositive(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
for (int i = 0; i < n; ++i)
{
if (A[i] > 0 && A[i] < n)
{
if (A[i]-1 != i && A[A[i]-1] != A[i])//let A[i] go the right place A[A[i]-1]
{
int tmp = A[A[i]-1];
A[A[i]-1] = A[i];
A[i] = tmp;
i--;//the element place where may be wrong
}
}
}
//check
for (int i = 0; i < n; ++i)
{
if(A[i] != i+1)
return i+1;
}
return n+1;
}
};
second time
class Solution {
public:
int firstMissingPositive(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
for(int i = 0; i < n; ++i)
{
int curNum = A[i];
while(curNum >= 1 && curNum <= n && A[curNum-1] != curNum)
{
int tmp = A[curNum-1];
A[curNum-1] = curNum;
curNum = tmp;
}
}
//find the first missing
int i;
for(i = 0; i < n; ++i)
if(A[i] != i+1) break;
return i+1;
}
};