首页 > 代码库 > 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.

思路:由于本题要求O(n)时间复杂度和常空间复杂度,所以考虑使用A辅助存储,直接将1,2,3,...k...交换到A[k-1]处。

 1 class Solution { 2 public: 3     int firstMissingPositive( int A[], int n ) { 4         int i = 0; 5         while ( i < n ) { 6             if( A[i] > 0 && A[i] < n && A[A[i]-1] != A[i] ) { 7                 swap( A[i], A[A[i]-1] ); 8             } else { 9                 ++i;10             }11         }12         for( i = 0; i < n && A[i] == i+1; ++i ) { ; }13         return i+1;14     }15 };

 

First Missing Positive