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: N number, the possible maximum positive integer is n, so you can use this n number as the hash value. But there is an extra space for O (n).
The solution is to reuse a[], first a[i] negative numbers are removed (marked as n+1), and secondly, when traversing to an integer cur, the a[cur] becomes the opposite number, so that the a[i]<0 I position I appeared, but also to ensure that the original value is not destroyed (can be obtained by ABS (A[i]) obtained.
classSolution { Public: intFirstmissingpositive (intA[],intN) {inti; for(i =0; I < n; i++) if(a[i]<=0) A[i] = n+1; for(i =0; I < n; i++) { if(ABS (A[i]) <= N) {//ABS is required because in the FOR loop we change the value of [1,n] to a negative number intCur = ABS (A[i])-1; A[cur]= -ABS (A[cur]); } } for(i =0; I < n; i++) { if(A[i] >0)returni+1; } returnn+1; }};
Missing Positive (MAP)