Both methods use the input array A. If I exists in a, a [I] is marked.
Because n elements in a have> N and <= 0, the first missing positive integer must be between [1-n + 1.
The first approach is to set the tag to a specific number. Because changing the value will affect the original stored value at this position, you need to process all the "original values" in one loop ".
For example, the array is {2, 3, 4, 1 }. For the first number 2, we mark the position (2-1) = 1 as-max_int, the array is changed to {2,-max_int,}, 3 is lost, therefore, the original values of the array should be recorded and the position (3-1) = 2 should be marked as-max_int...
int firstMissingPositive(int A[], int n) { for (int i = 0; i < n; i++) { int k = A[i]; while (k > 0 && k <= n) { int temp = A[k-1]; A[k-1] = - INT_MAX; k = temp; } } for (int i = 0; i < n; i++) if (A[i] != -INT_MAX) return i + 1; return n + 1; }
The second approach is to remove the while loop in for without changing the value.
What can we change without changing the value? We can change the symbol. In this way, the negative numbers that exist at the beginning of the array will affect the final result, so we do a preprocessing-convert all negative numbers into a number greater than N-int_max.
int firstMissingPositive(int A[], int n) { for (int i = 0; i < n; i++) { if (A[i] <= 0) A[i] = INT_MAX; } for (int i = 0; i < n; i++) { int k = abs(A[i]); if (k <= n) A[k-1] = - abs(A[k-1]); } for (int i = 0; i < n; i++) if (A[i] > 0) return i + 1; return n + 1; }
The time complexity of the two methods is O (n). To be precise, the array is traversed three times in the worst case.
Submission details [leetcode] ---- two ideas of inplace Linear Time