-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfind_first_missing_positive.cpp
More file actions
56 lines (50 loc) · 1.22 KB
/
find_first_missing_positive.cpp
File metadata and controls
56 lines (50 loc) · 1.22 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
56
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
/**
* Describe: Find the first missing positive number.
* Do it in O(n)
*/
class Solution {
public:
/**
* @param A: a vector of integers
* @return: an integer
*/
int firstMissingPositive(vector<int> A) {
int len = A.size();
int idx = 0;
// Make the correspond element to it correspond position in array.
while (idx < len) {
if (A[idx] > 0 && A[idx] <= len && idx + 1 != A[idx]
&& A[idx] != A[A[idx] - 1]) {
swap(A[idx], A[A[idx] - 1]);
} else {
idx++;
}
}
// Find the first missing number
for (int i = 0; i < len; i++) {
if (i + 1 != A[i]) {
return i + 1;
}
}
// Not found, returns len + 1
return len + 1;
}
};
int main() {
Solution so;
vector<int> test;
int n;
while (cin >> n) {
test = vector<int>(n);
for (int i = 0; i < n; ++i) {
cin >> test[i];
}
int re = so.firstMissingPositive(test);
cout << "result: " << re << endl;
}
return 0;
}