For example,
Given
and
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.
[Thoughts]:感觉有点点无理取闹的一个题。public class Solution {
public int firstMissingPositive(int[] A) {
int len = A.length;
for(int i=0; i<len; i++){
while(A[i] != i+1){
if(A[i]<=0 || A[i]>len || A[i]==A[A[i]-1])
break;
int temp = A[i];
A[i] = A[temp-1];
A[temp-1]=temp;
}
}
for(int j=0; j<len; j++){
if(A[j]!=j+1)
return j+1;
}
return len+1;
}
}
No comments:
Post a Comment