Skip to content

Commit 4635bb4

Browse files
committed
2
1 parent 97a1fc9 commit 4635bb4

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
class Solution {
2+
public:
3+
int firstMissingPositive(int A[], int n) {
4+
// Start typing your C/C++ solution below
5+
// DO NOT write int main() function
6+
7+
int i = 0;
8+
while (i < n) {
9+
if (A[i] != i + 1 && 0 < A[i] && A[i] <= n && A[A[i]-1] != A[i])
10+
swap(A[i], A[A[i]-1]);
11+
else
12+
i += 1;
13+
}
14+
int first_positive = 0;
15+
for (int i = 0; i < n; i++) {
16+
if (A[i] != i + 1) {
17+
first_positive = i + 1;
18+
break;
19+
}
20+
}
21+
if (first_positive == 0)
22+
first_positive = n + 1;
23+
return first_positive;
24+
}
25+
};
26+
27+
//
28+
// solution 2
29+
//
30+
class Solution {
31+
public:
32+
int firstMissingPositive(int A[], int n) {
33+
// Start typing your C/C++ solution below
34+
// DO NOT write int main() function
35+
36+
bool find_1 = false;
37+
for (int i = 0; i < n; i++) {
38+
if (A[i] == 1)
39+
find_1 = true;
40+
else if (A[i] <= 0)
41+
A[i] = 1;
42+
}
43+
if (!find_1) return 1;
44+
for (int i = 0; i < n; i++) {
45+
if (A[i] > 0 && A[i] <= n && A[A[i]-1] > 0) {
46+
A[A[i]-1] = -A[A[i]-1];
47+
}
48+
else if (A[i] <= -1 && -A[i] <= n && A[-A[i]-1] > 0)
49+
A[-A[i]-1] = -A[-A[i]-1];
50+
}
51+
int first_positive = 0;
52+
for (int i = 0; i < n; i++) {
53+
if (A[i] > 0) {
54+
first_positive = i + 1;
55+
break;
56+
}
57+
}
58+
if (first_positive == 0)
59+
first_positive = n + 1;
60+
return first_positive;
61+
}
62+
};

0 commit comments

Comments
 (0)