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.
[code]
public class Solution {
public int firstMissingPositive(int[] A) {
if(A==null || A.length==0)return 1;
int n=A.length;
for(int i=0;i<n;i++)
{
if(A[i]<=0 || A[i]>n || A[i]==i+1)continue;
if(A[i]!=A[A[i]-1])
{
swap(A, i, A[i]-1);
i--;
}
}
for(int i=0;i<n;i++)
{
if(A[i]!=i+1)
{
return i+1;
}
}
return n+1;
}
void swap(int[]A, int i, int j)
{
int temp=A[i];
A[i]=A[j];
A[j]=temp;
}
}
[Thoughts]
- 由于要constant space,只能把数组自己当成hashmap来用.
- A[i]==A[A[i]-1]会死循环