[leetcode_41]First Missing Positive

Initially I could only solve it using a map. But obviously that doesn’t meet the constant space requirement.
Reference:
http://blog.unieagle.net/2012/09/20/leetcode题目:first-missing-positive/

The DIY hash approach is clever.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
public:
    int firstMissingPositive(int A[], int n) {
        for(int i = 0; i < n; i++) {
            if(A[i] <= 0)
                A[i] = n+2;
        }
        for(int i = 0; i < n; i++) {
            if(abs(A[i]) - 1 < n && A[abs(A[i]) - 1] > 0)
                A[abs(A[i]) - 1] *= (-1);
        }
        for(int i = 1; i <= n; i++) {
            if(A[i-1] >= 0)
                return i;
        }
        return n + 1;
    }
};