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.
Solution One: O (nlogn) Time and O (1) space
No brain solution--First sort O (Nlogn)
Thoughts are as follows:
1, omit the number of non-positive prefixes.
2. Write down a positive integer to be matched as tag.
Consider repetition, if a[i] equals tag, then tag++
If A[i] is greater than tag, returns the tag
A[i] cannot be less than tag, which can be guaranteed by sequencing.
classSolution { Public: intFirstmissingpositive (intA[],intN) {if(n = =0) return 1; Sort (A,a+N); inti =0; while(I < n && A[i] <=0) I++; if(i = =N)return 1; intTag =1; for(; i < n; i + +)) { if(A[i] >tag)//miss the Tag returntag; Else if(A[i] = =tag)//Next PositiveTag + +; Else ; } //I==n, miss the tag returntag; }};
Solution two: O (n) time and O (n) space
A little thought would tell that an array of n capacity, with a maximum of the positive integers covered, is a continuous 1~n
In other words, a missing positive integer is either present in 1~n or n+1
You can therefore construct an array of size n Tag,tag[i] to record whether i+1 this number appears in a.
Returns N+1 if tag is true, otherwise returns the first tag with a negative label of +1
classSolution { Public: intFirstmissingpositive (intA[],intN) {if(n = =0) return 1; //Tag[i] means whether i+1 exists in A//at the most 1~n and then return n+1vector<BOOL> tag (n,false); for(inti =0; I < n; i + +) { if(A[i] >0&& A[i] <=N) tag[a[i]-1] =true; } for(inti =0; I < n; i + +) { if(Tag[i] = =false) returni+1; } returnn+1; }};
"Leetcode" First Missing Positive (2 solutions)