Sunday 17 July 2016

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
    Approach : Move negative elements to the right and the modify array for positive elements
*/

 #include <iostream>  
 #include<cmath>  
 using namespace std;  
 int firstMissingPositive(int* nums, int numsSize) {  
   int i, j = 0, k;  
   for(i = 0; i < numsSize; i++){  
     if(nums[i] > 0){  
       nums[j] = nums[i];  
       j++;  
     }  
   }  
   for(i = 0; i < j; i++){  
     k = abs(nums[i]) - 1;  
     if(nums[k] > 0 && k < j){  
       nums[k] = -1 * nums[k];  
     }  
   }  
   for(i = 0; i < j; i++){  
     if(nums[i] > 0){  
       return i + 1;  
     }  
   }  
   return j + 1;  
 }  
 int main(){  
   int arr[] = {2, 3, 4, -1, 1};  
   cout << firstMissingPositive(arr, sizeof(arr) / sizeof(arr[0]));  
   return 0;  
 }  
Share:

0 comments:

Post a Comment

Contact Me

Name

Email *

Message *

Popular Posts

Blog Archive