// Source : https://oj.leetcode.com/problems/first-missing-positive/ // Author : Hao Chen // Date : 2014-07-18 /********************************************************************************** * * 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. * * **********************************************************************************/ #include #include #include #include using namespace std; #define INT_MAX 2147483647 /* * Idea: * * We can move the num to the place whcih the index is the num. * * for example, (considering the array is zero-based. * 1 => A[0], 2 => A[1], 3=>A[2] * * Then, we can go through the array check the i+1 == A[i], if not ,just return i+1; * * This solution comes from StackOverflow.com * http://stackoverflow.com/questions/1586858/find-the-smallest-integer-not-in-a-list */ int firstMissingPositive_move(int A[], int n) { if (n<=0) return 1; int num; for(int i=0; i0 && num missed 0 * [4,5,6] => missed 3 * * However, we missed 1, so, we have to add dummy number 0 whatever. * * NOTE: this solution is not constant space slution!!!! * */ int firstMissingPositive_map(int A[], int n) { map cache; for(int i=0; i0; i++){ if (i == -1){ x = 0; //checking dummy }else{ x = A[i]; } if ( cache.find(x)==cache.end() ){ continue; } int num ; // remove the ... x-3, x-2, x-1, x for( num=x; cache.find(num)!=cache.end(); num--){ cache.erase(cache.find(num)); } if ( num>0 && num < miss ){ miss = num; } // remove the x+1, x+2, x+3 ... for ( num=x+1; cache.find(num)!=cache.end(); num++){ cache.erase(cache.find(num)); } if ( num>0 && num < miss) { miss = num; } } return miss; } int firstMissingPositive(int A[], int n) { srand(time(0)); if (rand()%2){ return firstMissingPositive_move(A, n); } return firstMissingPositive_map(A, n); } void printArray(int a[], int n){ cout << "[ "; for(int i=0; i