//bucket sort with constant space
public int firstMissingPositive(int[] A) {
// Start typing your Java solution below
// DO NOT write main() function
if(A == null || A.length == 0) return 1;
int tmp = 0;
for(int i = 0; i < A.length; i++) {
if(A[i] > 0 && A[i] <= A.length) {
if(A[i] != i + 1 && A[A[i] - 1] != A[i]) { //pay attention here
tmp = A[A[i] - 1];
A[A[i] - 1] = A[i];
A[i] = tmp;
i--;// pay attention here
}
}
}
for(int i = 0; i < A.length; i++) {
if(A[i] != i + 1) return i + 1;
}
return A.length + 1;
}
First Missing Positive
最新推荐文章于 2020-01-06 11:03:15 发布