-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFirstMissingInteger.cpp
More file actions
48 lines (43 loc) · 833 Bytes
/
FirstMissingInteger.cpp
File metadata and controls
48 lines (43 loc) · 833 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*Question
First Missing Integer
Asked in:
Model N
InMobi
Amazon
Given an unsorted integer array, find the first missing positive integer.
Example:
Given [1,2,0] return 3,
[3,4,-1,1] return 2,
[-8, -7, -6] returns 1
Your algorithm should run in O(n) time and use constant space.*/
void foo(vector<int> &a)
{
int j=0;
for(int i=0;i<a.size();i++)
{
if(a[i]<=0)
{
swap(a[i],a[j]);
j++;
}
}
a.erase(a.begin(),a.begin()+j);
}
int Solution::firstMissingPositive(vector<int> &A) {
foo(A);
// cout<<A.size()<<endl;
for(int i:A)
{
if(abs(i)<=A.size())
{
//cout<<i<<endl;
A[abs(i)-1]*=-1;
}
}
for(int i=0;i<A.size();i++)
{
if(A[i]>0)
return i+1;
}
return A.size()+1;
}