The original title link is here: https://leetcode.com/problems/first-missing-positive/
Two times scan, first time swap a[i] and it corresponds to the position element A[a[i]-1].
The second time to find if there is a[i]! = i+1, if any, return to i+1, if not, return a.length+1.
Note: The first scan when the swap condition is a[i] greater than 0 and less than equal to A.length, so a[i]-1 have a corresponding position, and exclude a[i] = = A[a[i]-1] Situation, that is, two points are the same, do not need swap, otherwise trapped infinite.
When doing this swap, pay attention to whether the swap is the same and will cause infinite loop.
i--is guaranteed after swap I return to the original position.
AC Java:
1 Public classSolution {2 Public intFirstmissingpositive (int[] A) {3 if(A = =NULL|| A.length = = 0){4 return1;5 }6 //First iteration, swap a[i] to its corresponding position a[a[i]-1]7 for(inti = 0; i<a.length; i++){8 if(a[i]>0 && a[i]<=a.length && a[i]!=a[a[i]-1]){9Swap (A, I, a[i]-1);Teni--; One } A } - //Second Iteration, return i+1 if a[i]! = i+1 - for(inti = 0; i<a.length; i++){ the if(A[i]! = i+1){ - returnI+1; - } - } + //All correspond, return a.length+1 - returnA.length + 1; + } A Public voidSwapint[] A,intIintj) { at inttemp =A[i]; -A[i] =A[j]; -A[J] =temp; - } -}
Leetcode First Missing Positive