[Leetcode 96] 41 First Missing Positive
Problem:
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 should run in O(n) time and uses constant space.
Analysis:
At first thought, hash table can be used in this problem. First hash all the numbers in the given array with O(n) time complexity, then search from 1 until the first missing positive number which also takes O(n) time complexity. But the requirement only allows constant space, so this is not good enough. And the way we can solve the problem is to use some in-place method. The method is as follows: everytime, swap the current element with value a with the A[a-1] place. Thus, A[0] stores 1, A[1] stores 2, etc. After the swap, if the new element in this palce is less than or equal to 0 or happened to be the element should be here, then we move to the next position, else we continue to swap at this position.
The skip condition is as follows: 1. A[i] <=0; 2. A[i] == i+1; 3. A[i] >= n; 4. A[i] == A[A[i]-1]
Code:
Hashtable Version:
1 class Solution { 2 public: 3 int firstMissingPositive(int A[], int n) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 unordered_set<int> us; 7 8 for (int i=0; i<n; i++) { 9 us.insert(A[i]); 10 } 11 12 int ms=1; 13 while (ms <= n) { 14 if (us.find(ms) == us.end()) 15 return ms; 16 17 ms++; 18 } 19 20 return ms; 21 } 22 };
Swap Version:
1 class Solution { 2 public: 3 int firstMissingPositive(int A[], int n) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 int tmp; 7 8 for (int i=0; i<n; ) { 9 if (A[i] > 0 && A[i] != i+1 && A[i] < n) { 10 tmp = A[A[i]-1]; 11 A[A[i]-1] = A[i]; 12 A[i] = tmp; 13 } 14 15 if (A[i] <= 0 || A[i] == i+1 || A[i] == A[A[i]-1] || A[i] >=n) 16 i++; 17 } 18 19 int i=0; 20 while (i<n) { 21 if (A[i] != i+1) 22 return i+1; 23 24 i++; 25 } 26 27 return i+1; 28 } 29 };