LeetCode, leetcodeoj
Link: First Missing Positive
Given an unsorted integer array, find the first missing positive integer.
For example,
Given [1,2,0] return 3, and [3,4,-1,1] return 2.
Your algorithm shocould run in O (n) time and uses constant space.
The requirement for this question is to find the first missing positive integer in array A (unordered. Requires O (n) time complexity.
The direct idea of this question is to sort it first, and then traverse it to find the first missing positive integer. However, the time complexity is O (nlogn ).
The question requires O (n) time complexity, so can it be faster? You can consider sorting. Similar to the idea of counting and sorting, apply for an empty array B of the same size, and then specify array, place the number that appears in A in B corresponding to the position of B's lower mark (if the number size exceeds the range of B, it is not processed ), for example, put 5 in B [4. Finally, traverse array B to find the first missing positive integer.
Since the array B applied for above is as big as array A, can we directly use array A instead of array B? Of course, when traversing A, if the number and position do not match, you can switch to the corresponding position.
Time Complexity: O (n)
Space complexity: O (1)
1 class Solution 2 { 3 public: 4 int firstMissingPositive(int A[], int n) 5 { 6 for(int i = 0; i < n; ++ i) 7 while(A[i] > 0 && A[i] <= n && A[A[i] - 1] != A[i]) 8 swap(A[i], A[A[i] - 1]); 9 10 for(int i = 0; i < n; ++ i)11 if(A[i] != i + 1)12 return i + 1;13 14 return n + 1;15 }16 };
Reprinted please note the Source: LeetCode --- 41. First Missing Positive