Problem

Given an unsorted integer array, find the first missing positive integer.

Example

Given [1,2,0] return 3,
and [3,4,-1,1] return 2.

Note

找第一个缺失的正整数,只要先按顺序排列好[1, 2, 3, 4, ...],也就是A[i] = i+1,找到第一个和A[i]不对应的数i+1就可以了。注意数组的index从0开始,而正整数从1开始,所以重写排列的时候要注意换成index-1,而index就是从A[0]开始的数组A[]中的元素。
我们看一个例子:

[2, 4, -1, 1] --> first for loop --> if (A[i] E (0, A.length) && A[i] != A[A[i]-1]) --> swap(A[i], A[A[i]-1]) --> [4, 2, -1, 1] --> [1, 2, -1, 4] --> second for loop --> A[2] != 3 --> return 2+1 = 3.

之前犯了一个错误,因为第二行A[i]的值已经变了,第三行再代入A[A[i]-1]就会出错:

int temp = A[i];
A[i] = A[A[i]-1];
A[A[i]-1] = temp;

Solution

public class Solution {
    public int firstMissingPositive(int[] A) {
        int len = A.length;
        for (int i = 0; i < len; i++) {
            if (A[i] > 0 && A[i] < len && A[i] != A[A[i]-1]) {
                int temp = A[A[i]-1];
                A[A[i]-1] = A[i];
                A[i] = temp;
                i--; //after the exchange, we need to speculate 
                     //and sort that digit again.
            }
        }
        for (int i = 0; i < len; i++) {
            if (A[i] != i + 1) return i+1; //as array index starts from 0 
                                           //and positive starts from 1.
        }
        return len + 1; //if the array has 1(A[0]) to len(A[len-1])
                        //and missed no one, return the len+1.
    }
}

linspiration
161 声望53 粉丝