Friday, February 7, 2014

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.
Solution:
all the numbers are in their correct positions. What are correct positions? For any i, A[i] = i+1.
it should be: A[0] = 1; A[1] = 2; A[2] = 3...

// A[] should be A[0] == 1, A[1] == 2, ...
public class Solution {
    public int firstMissingPositive(int[] A) {
        for(int i = 0; i < A.length; i++){
            while(A[i] != i + 1){
                // not whthin the range or no need to swap
                if(A[i] <= 0 || A[i] > A.length || A[i] == A[A[i] - 1]) 
                    break;
                // put what at A[i] to its desired position.
                int tmp = A[i];
                A[i] = A[tmp - 1];
                A[tmp - 1] = tmp;
            }
        }
        for(int i = 0; i < A.length; i++){
            if(A[i] != i + 1)
                return i + 1;
        }
        return A.length + 1;
    }
}

No comments:

Post a Comment