Search This Blog

Friday, December 21, 2012

LeetCode:First Missing Positive

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) {
        // Start typing your Java solution below
        // DO NOT write main() function
        int i=0, j=A.length-1;
        while(i<=j){
            while(i<A.length && A[i]>0) i++;
            while(j>=0 && A[j]<=0)j--;
            if(i<j){
                swap(A,i,j);
                i++;
                j--;
            }
        }
        for(i=0;i<j+1;i++){
            int temp = Math.abs(A[i]);
            if(temp<=j+1){
                if(A[temp-1]>0)
                    A[temp-1]=-A[temp-1];
            }
        }
        for(i=0;i<j+1;i++){
            if(A[i]>0) return i+1;
        }
        return i+1;
    }
    
    public void swap(int[] A, int x, int y){
        assert(A!=null && x>=0 && x<A.length && y>=0 && y<A.length);
        int temp = A[x];
        A[x]=A[y];
        A[y]=temp;
    }
}

No comments: