[leetcode] First Missing Positive

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.

class Solution {
public:
    int firstMissingPositive(int A[], int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int i;
        int *p=new int[n];
        memset(p,0,sizeof(int)*n);
        for(i=0 ; i<n ; i++){
            if(A[i]>0 && A[i]<=n)
                p[A[i]-1]=1;
        }
        for(i=0;i<n;i++){
            if(p[i]==0)
                return i+1;
        }
        if(i==n)
            return n+1;
    }
};


你可能感兴趣的:([leetcode] First Missing Positive)