First Missing Positive

来源:互联网 发布:淘宝上好看的包包店铺 编辑:程序博客网 时间:2024/06/07 07:23

Method 1:  reference   http://www.geeksforgeeks.org/find-the-smallest-positive-number-missing-from-an-unsorted-array/

First split the array into negative part and positive part. 

The negative part can be ignored, while for the positive part, for each element i, if i<size, when we mark array[i-1] as negative, meaning that positive integer i has occurred.

after all marking, scan the array again to find the first positive place j, then j+1 is the first missing positive integer.

Code: (8ms AC)

class Solution {public:    int firstMissingPositive(int A[], int n) {        int positionStart = split(A, n);        return findFirstMissing(A+positionStart, n-positionStart);    }        int findFirstMissing(int A[], int size)    {        for(int i=0; i<size; i++)        {            if(abs(A[i])-1 < size && A[abs(A[i])-1] > 0)                A[abs(A[i])-1] = -A[abs(A[i])-1];        }        for(int i=0; i<size; i++)            if(A[i] > 0)                return i+1;        return size+1;    }        int split(int A[], int size)    {        int j=0;        for(int i=0; i<size; i++)        {            if(A[i] <= 0)            {                swap(A+i, A+j);                j++;            }        }        return j;    }        void swap(int *a, int *b)    {        int tmp = *a;        *a = *b;        *b = tmp;    }};

Method 2: use bucket sort. refer leetcode solution.

for each index i, if A[i] not equals i+1, then swap A[i] with A[ A[i]-1 ] until A[i] exceeds the array range or A[i] == A[ A[i]-1 ]

code: (40ms AC)

class Solution {public:    int firstMissingPositive(int A[], int n) {        bucket_sort(A, n);        for(int i=0; i<n; i++)            if(A[i] != i+1)                return i+1;        return n+1;    }        void bucket_sort(int A[], int n)    {        for(int i=0; i<n; i++)        {            while(A[i] != i+1)            {                if(A[i] <= 0 || A[i] > n || A[i] == A[A[i]-1])                    break;                swap(A+i, A+A[i]-1);            }        }    }        void swap(int *a, int *b)    {        int tmp = *a;        *a = *b;        *b = tmp;    }};

0 0
原创粉丝点击