Skip to content

Commit 076ad39

Browse files
committed
Solution as on 22-03-2022 08:45 pm
1 parent 85ceee8 commit 076ad39

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

0041. First Missing Positive.cpp

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
// 41.✅ First Missing Positive
2+
3+
class Solution
4+
{
5+
public:
6+
int firstMissingPositive(vector<int> &nums)
7+
{
8+
set<int> s;
9+
int ans = 1;
10+
for (int i = 0; i < nums.size(); ++i)
11+
s.insert(nums[i]);
12+
13+
for (int i = 1; i <= nums.size() + 1; ++i)
14+
{
15+
auto it = s.find(i);
16+
if (it == s.end())
17+
{
18+
ans = i;
19+
break;
20+
}
21+
}
22+
23+
return ans;
24+
}
25+
};
26+
27+
// Another Approach
28+
29+
class Solution
30+
{
31+
public:
32+
int firstMissingPositive(vector<int> &nums)
33+
{
34+
bool contains_one = false;
35+
for (int x : nums)
36+
{
37+
if (x == 1)
38+
{
39+
contains_one = true;
40+
break;
41+
}
42+
}
43+
44+
if (!contains_one)
45+
return 1;
46+
47+
int n = nums.size();
48+
if (n == 1)
49+
return 2;
50+
51+
for (int i = 0; i < n; ++i)
52+
{
53+
if (nums[i] <= 0 || nums[i] > n)
54+
nums[i] = 1;
55+
}
56+
57+
for (int i = 0; i < n; ++i)
58+
{
59+
int x = abs(nums[i]);
60+
if (nums[x - 1] > 0)
61+
nums[x - 1] *= -1;
62+
}
63+
64+
for (int i = 0; i < n; ++i)
65+
{
66+
if (nums[i] > 0)
67+
return i + 1;
68+
}
69+
70+
return n + 1;
71+
}
72+
};

0 commit comments

Comments
 (0)