題目描述
Given an unsorted integer array, find the first missing positive integer.
For example,
Given[1,2,0]return3,
and[3,4,-1,1]return2.
Your algorithm should run in O(n) time and uses constant space.
分析思路
如果用排序,時間複雜度也要nO(logn),如果用map,需要O(n)的空間。
採用如下思路;
將值放在它應該在的位置,最後再掃描一次得出哪個位置有缺少值。
如果該值小於0,忽略它;
如果該值大於0,A[i] = x,我們知道它應該被放在A[x-1]處,也就是交換A[i]與A[A[i]-1]
java實現
public int firstMissingPositive(int[] A) {
int i;
int n = A.length;
for(i=0; i<n;){
if(A[i]!= i+1 && A[i]>=1&&A[i]<=n && A[i] != A[A[i]-1]){
swap(A, i, A[i]-1);
}else
++i;
}
for(i=0; i<n;i++){//掃描,
if(A[i] != i+1){
return i+1;
}
}
return n+1;
}
public void swap(int[] A, int i, int j){
if(i != j){
A[i] ^= A[j];
A[j] ^= A[i];
A[i] ^= A[j];
}
}
}