public int firstMissingPositive(int[] A) {

    for (int i = 0 ; i < A.length ;) {
      if (A[i] != i + 1 && A[i] < A.length && A[i] > 0) {
        // deal with duplicate elements
        if (A[i] == A[A[i] - 1]) {
          i++;
          continue;
        }
        // swap A[i] and A[A[i]-1]
        int temp = A[i];
        A[i] = A[temp - 1];
        A[temp - 1] = temp;
      } else {
        i++;
      }
    }

    for (int i = 0 ; i < A.length ; i++) {
      if (A[i] != i + 1) {
        return i + 1;
      }
    }

    // cannot simply return 0 or 1
    // return 0
    return A.length + 1;
  }