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.
这题的基本解法是用数组元素本身作为下标,把i+1放到A[i]里面去(当然要交换数组元素,不能把A[i]的元素丢掉)。如果是超出数组下标允许范围的元素(<0或>=A.length)就不管它,放在原处。这样子[3,4,-1,1]经过一次循环后会变成[1,-1,3,4]。然后再一遍循环,看A[i]==i+1.不是的话那么就返回i+1.
public class Solution {
public int firstMissingPositive(int[] A) {
int index = 0;
while(index < A.length){
if(A[index] >= 1 && A[index] <= A.length && A[index] != index + 1 && A[A[index] - 1] != A[index]){
swap(A, index, A[index] - 1);
}
else{
index++;
}
}
for(int i = 0; i < A.length; i++){
if(A[i] != i + 1){
return i + 1;
}
}
return A.length + 1;
}
public void swap(int[] A, int i, int j){
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
}