Leetcode: 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 should run in O(n) time and uses constant space.
Naive的方法肯定是sort这个数组,但那样要用O(NlongN)的时间;第二种思路是用哈希表映射,Mapping all positive integers to a hash table and iterate from 1 to the length of the array to find out the first missing one,但哈希表是O(N)的space. 那怎么做呢?
Li Shi's Analysis:
The idea is to use the array itself as a table. We try put a value i on the place i-1. If the value i is out of range, i.e., <=0 || >n, then ignore it. At each position i, we check whether the A[i] is a value needed to be placed on its own position, if yes, we swap it; then we check the new A[i] again. We repeat this procedure until A[i] is a value that is out of range or the right place of value A[i] is already placed a value of A[i] (Duplicate situation), we then move the i+1 position.
不能开辟非常数的额外空间,就需要在原数组上操作,思路是交换数组元素,让数组中index为i的位置存放数值(i+1)。最后如果哪个数组元素违反了A[i]=i+1即说明i+1就是我们要求的第一个缺失的正数。具体操作如下:
- if A[i] is positive, say we have A[i] = x, we know it should be in slot A[x-1]! That is to say, we can swap A[x-1] with A[i] so as to place x into the right place.
- if A[i] is non-positive, 0, or A[i]>A.length, ignore it;
- if A[i] == A[A[i]-1], we do not swap, two cases, 1. Maybe A[i] = i+1, A[i]is correct; 2. though A[i] is not correct like [1, 1] index 1, but A[0] == A[1], swap A[1] with A[0] will only give rise to infinite loop
1 public class Solution { 2 public int firstMissingPositive(int[] A) { 3 if (A==null && A.length==0) { 4 return 1; 5 } 6 for (int i=0; i<A.length; i++) { 7 if (A[i]>0 && A[i]<=A.length && A[i]!=A[A[i]-1]) { 8 int temp = A[A[i]-1]; 9 A[A[i]-1] = A[i]; 10 A[i] = temp; 11 i--; 12 } 13 } 14 15 for (int i=0; i<A.length; i++) { 16 if (A[i] != i+1) return i+1; 17 } 18 return A.length+1; 19 } 20 }
有个细节是8-10行交换两个元素,不能先改动A[i],这样A[A[i]-1]会变。结果就是无限循环。一定要先改A[A[i]-1]。
实现中还需要注意一个细节,第7行,一定是A[i]跟A[A[i]-1]比,而不能是跟i+1比(会出现无限循环,比如输入[1, 1])。就是如果当前的数字所对应的下标已经是对应数字了,那么我们也需要跳过,因为那个位置的数字已经满足要求了,否则会出现一直来回交换的死循环。这样一来我们只需要扫描数组两遍,时间复杂度是O(2*n)=O(n),而且利用数组本身空间,只需要一个额外变量,所以空间复杂度是O(1)。
Naive方法,时间复杂度O(NlogN), Analysis: 第一次写的时候没有考虑到数组元素有可能重合的问题
1 public class Solution { 2 public int firstMissingPositive(int[] A) { 3 int shouldbe = 1; 4 int store = 0; 5 java.util.Arrays.sort(A); 6 for (int elem : A) { 7 if (elem > 0) { 8 if (elem == store) continue; 9 else if (elem == shouldbe) { 10 shouldbe++; 11 store = elem; 12 } 13 else break; 14 } 15 } 16 return shouldbe; 17 } 18 }