Monday, December 29, 2014

First Missing Positive (LeetCode Array)

Question:  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.

Idea: Assume there is a perfect array without any missing number in the middle, e.g. [1,2,3,4,5,6,..., n-1,n], the first missing positive number is n+1. However, some of the values in the perfect array may be missing and some numbers in the range (-infinite,0) and (n+1, +infinite) may be mixed together with the perfect array.

So the idea of looking for the first missing positive is to reconstruct the perfect array.  Assume the length of the input array is N, the corresponding perfect array is (1,2,...,N). Then we scan the input array from left to right, and try to put the numbers i from perfect array to index i-1, e.g. number 1 to index 0. Finally we scan the modified array to test whether there is an number missing from the perfect array, where missing means number i is not at index i-1, e.g. 1 is not at index 0.

Time: O(n) Space: O(1)

Code:  
 public class Solution {  
   public int firstMissingPositive(int[] A) {  
     bucketSort(A);  
     for(int i=0;i<A.length;i++)  
     {  
       if(A[i]!=i+1)  
         return i+1;  
     }  
     return A.length+1;  
   }  
   public void bucketSort(int[] A)  
   {  
     for(int i=0;i<A.length;i++)  
     {  
       while(A[i]!=i+1)  
       {  
         if(A[i]<=0||A[i]>A.length||A[i]==A[A[i]-1])  
           break;  
         else  
           swap(A,i,A[i]-1);  
       }  
     }  
   }  
   public void swap(int[] A,int i,int j)  
   {  
     int tmp=A[i];  
     A[i]=A[j];  
     A[j]=tmp;  
   }  
 }  

No comments:

Post a Comment