-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathLC_41_FirstMissingPositive.cpp
102 lines (84 loc) · 2.39 KB
/
LC_41_FirstMissingPositive.cpp
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/*
https://leetcode.com/problems/first-missing-positive/
41. First Missing Positive
*/
class Solution {
public:
int firstMissingPositive_2(vector<int>& nums) {
int n=nums.size();
vector<bool> vis(n+1);
for(int x: nums)
if(x>0 and x<=n)
vis[x]=true;
for(int i=1; i<=n; i++)
if(!vis[i])
return i;
return n+1;
}
int firstMissingPositive_1(vector<int>& nums) {
int ans=1;
priority_queue<int, vector<int>, greater<int>> pq(nums.begin(), nums.end());
while(!pq.empty())
{
int ele = pq.top();
if(ele > 0)
{
if(pq.top() == ans)
ans++;
// else
// return ans;
}
pq.pop();
}
return ans;
}
int firstMissingPositive_3(vector<int>& nums) {
int n = nums.size();
int max_pos_num = n+1;
//modifying the input array
for(int i=0; i<n; i++)
{
if(nums[i] <=0 || nums[i] > max_pos_num)
nums[i] = max_pos_num;
}
for(int i=0; i<n; i++)
{
int val = abs(nums[i]);
if(val <= n && nums[val-1]>0) //val should be <=n and +ve to negative kr do
nums[val-1] *=-1;
}
for(int i=0; i<n; i++)
if(nums[i] > 0)
return i+1;
return max_pos_num;
}
int firstMissingPositive(vector<int>& nums) {
int n = nums.size();
bool isFirstPresent=false;
//modifying the input array
for(int i=0; i<n; i++)
{
if(nums[i]==1) isFirstPresent=true;
if(nums[i] <=0 || nums[i] > n)
nums[i]=1;
}
if(!isFirstPresent) return 1;
// cout<<endl;
// for(int x: nums)
// cout<<x<<" ";
for(int i=0; i<n; i++)
{
int val = abs(nums[i]);
// int ele = nums[val-1];
if(nums[val-1]>0)
nums[val-1] *= -1;
}
// cout<<endl;
// for(int x: nums)
// cout<<x<<" ";
for(int i=0; i<n; i++)
if(nums[i] > 0)
return i+1;
return n+1;
}
};