1 public class Solution { 2 public int firstMissingPositive(int[] A) { 3 // IMPORTANT: Please reset any member data you declared, as 4 // the same Solution instance will be reused for each test case. 5 int len = A.length; 6 for (int i = 0; i < len; i++) { 7 //use a while to put the element to correct place 8 while (A[i] > 0 && A[i] != i + 1 && A[i] <= len) { 9 if (A[i] == A[A[i] - 1]) 10 break; 11 int tmp = A[i]; 12 A[i] = A[A[i] - 1]; 13 A[tmp - 1] = tmp; 14 } 15 16 } 17 int idx = 0; 18 for (; idx < len; idx++) { 19 if (A[idx] < 0 || A[idx] != idx + 1) { 20 return idx + 1; 21 } 22 } 23 24 return idx + 1; 25 } 26 }