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.
public class Solution {
public int firstMissingPositive(int[] A) {
int len=A.length;
if(len==0)return 1;
for(int i=0;i<len;i++){
int cur=A[i];
if(cur==i+1||cur<=0||cur>=len)continue;
A[i]=A[cur-1];
A[cur-1]=cur;
if(A[i]!=A[cur-1])i--;// if not equal, we should do it again
}
for(int i=0;i<len;i++){
if(A[i]!=i+1)
return i+1;
}
return len+1;
}
}
1 The thought is that put everything in the place that it should be.. Then the first obey it is the first missing element.
2 after swapping, the only condition that we don't need to do it again is that the two elements are the same.