LeetCode_FirstMissingPositive

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

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

Your algorithm should run in O(n) time and uses constant space.

int firstMissingPositive(int A[], int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (n == 0)
        {
            return 1;
        }
        for (int i = 0; i < n; ++i)
        {
            while (0 < A[i] && A[i] <= n && A[i] != i + 1)
            {
                int tmp = A[A[i] - 1];
                A[A[i] - 1] = A[i];
                if (tmp == A[i] || tmp <= 0 || tmp > n || A[i] < i)
                {
                    break;
                }
                A[i] = tmp;
            }
        }
        for (int i = 0; i < n; ++i)
        {
            if (A[i] != i + 1)
            {
                return (i + 1);
            }
        }
        return (n + 1);
    }


你可能感兴趣的:(LeetCode)