Monday, November 25, 2013

LeetCode Problem : First Missing Positive

Problem


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.

Code

int firstMissingPositive(int A[], int n) {
    // Note: The Solution object is instantiated only once and is reused by each test case.
    int i = 0;
    while(i < n){
        while(A[i] > 0 && A[i] <= n && A[i] != i + 1 && A[A[i] - 1] != A[i]){
            swap(A[i],A[A[i] - 1]);
        }
        ++i;
    }
    i = 0;
    while(i < n){
    if(A[i] != i + 1)
        return i + 1;
    ++i;
    }
    return n + 1;
}

No comments:

Post a Comment