-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathfirst-missing-integer.cpp
More file actions
55 lines (47 loc) · 1.03 KB
/
first-missing-integer.cpp
File metadata and controls
55 lines (47 loc) · 1.03 KB
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
49
50
51
52
53
54
55
int segregate(vector<int> &A)
{
int j = 0;
for(int i = 0; i < A.size(); i++) {
if(A[i] > 0) {
if(i != j) {
swap(A[i], A[j]);
}
j++;
}
}
return j;
}
int Solution::firstMissingPositive(vector<int> &A) {
int n = segregate(A);
for(int i = 0; i < n; i++) {
int index = abs(A[i]) - 1;
if(index < n && A[index] > 0) {
A[index] = -A[index];
}
}
for(int i = 0; i < n; i++) {
if(A[i] > 0) {
return i + 1;
}
}
return n + 1;
}
// Another shorter way
int Solution::firstMissingPositive(vector<int> &A) {
int n = A.size();
for(int i = 0; i < n; i++) {
if(A[i] > 0 && A[i] <= n) {
int index = A[i] - 1;
if(A[index] != A[i]) {
swap(A[i], A[index]);
i--;
}
}
}
for(int i = 0; i < n; i++) {
if(A[i] != i + 1) {
return i + 1;
}
}
return n + 1;
}