首页 > 代码库 > First Missing Positive

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.

采用hash的思路,将A[i]的当做索引,标记对应的A[A[i]-1]为-,  最后遍历,为正的则为缺失的

 

 

    int firstMissingPositive(int A[], int n) {        for (int i=0; i<n; i++)        {            if (A[i] <= 0)                A[i] = n+2;        }                for (int i=0; i<n; i++)        {            int nTmp = abs(A[i]);            if (nTmp<1 || nTmp>n)                continue;                        if (A[nTmp-1] > 0)                A[nTmp-1] *= -1;        }                for (int i=0; i<n; i++)        {            if (A[i] > 0)                return i+1;        }                return n+1;    }

 

First Missing Positive