First Missing Positive

唉 想了很久都没想出来 后来还是看了网上的答案 >_<
public class Solution {
    public int firstMissingPositive(int[] A) {
        // Start typing your Java solution below
        // DO NOT write main() function

        //put i to A[i-1], so the array looks like: 1, 2, 3, ...

        for (int i = 0; i < A.length; i++) {
            while (A[i] != i+1) {
                if (A[i] <= 0 || A[i] > A.length || A[i] == A[A[i] - 1]) {
                    break;
                }

                int tmp = A[A[i]-1];
                A[A[i]-1] = A[i];
                A[i] = tmp;
            }
        }

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

你可能感兴趣的:(first)