Two methods:
1. Use extra memory:
1 class Solution { 2 public: 3 int firstMissingPositive(int A[], int n) { 4 unordered_set<int> sets; 5 int result = 1; 6 for (int i = 0; i < n; i++) sets.insert(A[i]); 7 while (sets.find(result++) != sets.end()); 8 return result-1; 9 } 10 };
2. In place:
The trick is the relationship between value and index. Since it is first missing positive number, if the number is not missing, it should satisfy index + 1 = value in [1, n].
1 class Solution { 2 public: 3 int firstMissingPositive(int A[], int n) { 4 if (n == 0) return 1; 5 int i = 0; 6 while (i < n) { 7 if (A[i] > 0 && A[i] <= n && A[i] != i+1 && A[A[i]-1] != A[i]) { 8 [](int &a, int &b){int t = a; a = b; b = t;}(A[i], A[A[i]-1]); 9 continue; 10 } 11 i++; 12 } 13 for (i = 0; i < n; i++) { 14 if (A[i] != i+1) break; 15 } 16 return i+1; 17 } 18 };