Thursday, January 8, 2015

LeetCode 41: 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.
public class Solution {
    public int firstMissingPositive(int[] A) {
        // Put the element, which value is i, in position i – 1.
        // After finishing doing this, go through the array to find the first missing positive integer.        
        int n = A.length;
        int i = 0;
        
        while (i < n)
        {
            if (A[i]>=1 && A[i]<=n && A[i]!=i+1 && A[A[i]-1]!=A[i])
                swap(A, i, A[i]-1);
            else
                i++;
        }
        
        for (i = 0; i < n; i++)
            if (A[i] != i+1)
                return i+1;
                
        return n+1;
    }
    
    private void swap(int[] A, int i, int j)
    {
        int tmp = A[i];
        A[i] = A[j];
        A[j] = tmp;
    }
}

No comments:

Post a Comment