Back to Leetcode
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.
Solution:read blog :http://www.cnblogs.com/AnnieKim/archive/2013/04/21/3034631.html
very clear explanation
One thing for remark:
when swap,
int tmp = A[i];
so next,
A[i] = A[tmp-1]; A[tmp-1] = tmp;
not A[i] = A[A[i]-1]; A[A[i]-1] = tmp
Because A[i] already changed. This may cause TLE
Be careful to details
public int firstMissingPositive(int[] A) {
//using O(n) time: operate swap on array
if(A.length < 1) return 1;
int i = 0;
while(i < A.length){
if(A[i] != i+1 && A[i] >=1 && A[i] <= A.length && A[A[i]-1] != A[i]){
// if element <0 or element > n, ignore
//swap A[i] = A[A[i]-1]
int tmp = A[i];
A[i] = A[tmp-1]; // A[tmp-1], A[A[i]-1] is incorrect
A[tmp-1] = tmp;
}
else i++;
}
int j = 0;
for(j=0; j<A.length; j++){
if(A[j] != j+1){
return j+1;
// break;
}
}
return A.length+1;
}