思路1: 直接暴力解決,複雜度O(N*N)
代碼1:
public int firstMissingPositive1(int[] A) {// big O(N*N)
if(A.length == 0)return 1;
int i = 1;
while(i <= A.length){
boolean isfind = false;
for(int j = 0; j< A.length; ++j){
if(A[j] == i){
isfind = true;
break;
}
}
if(!isfind) break;
i ++;
}
return i;
}
思路2:先排序,然後遍歷,複雜度(N*log(N))
代碼:
public int firstMissingPositive2(int[] A) {//sort First O(N*log(N))+O(N)
if(A.length == 0)return 1;
Arrays.sort(A);
int currNotFind = 1, i = 0;
while(i <= A.length){
if(currNotFind == A[i]){
currNotFind ++ ;
i++;
}else if(currNotFind < A[i]){
return currNotFind ;
}else {
i ++;
}
}
return currNotFind;
}
思路3:開闢一個n個元素的數組空間,然後記錄對應的數是否存在,空間和時間複雜度都是O(N)代碼:
public int firstMissingPositive3(int[] A) {//O(N) and O(N)space
if(A.length == 0)return 1;
int [] find = new int[A.length + 1];
for (int i =0; i < A.length; ++i){
if(A[i] > 0 && A[i] <= A.length){
find[A[i]-1] = 1;
}
}
for (int i = 0; i <= A.length; ++i){
if(find[i] == 0)return i+1;
}
return 1;
}
思路4:不開劈額外空間,但是這需要在元數組中進行置換,將元素i放到數組中的i-1的位置上去,空間複雜度O(1),時間複雜度O(N)
代碼:
public int firstMissingPositive(int[] A) {//O(N) and O(1)
if(A.length == 0)return 1;
int temp =0;
for (int i =0; i < A.length;){
if(A[i] != (i+1) && A[i] >= 1 && A[i] <= A.length && A[A[i]-1] != A[i]){
temp = A[i];
A[i] = A[temp - 1];
A[temp-1] = temp;
}else ++i;
}
int i = 0;
for (i = 0; i < A.length; ++i){
if(A[i] != i+1)return i+1;
}
return A.length + 1;
}