First Missing Positive

来源:互联网 发布:alexnet网络详解 编辑:程序博客网 时间:2024/05/22 08:13

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

思路参考了http://blog.csdn.net/pickless/article/details/9234301

大多数人也采用的是让原数组多带些信息(采用负号)来实现hash。

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


0 0
原创粉丝点击