-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path16_Kth_Missing.cpp
More file actions
101 lines (63 loc) · 1.9 KB
/
16_Kth_Missing.cpp
File metadata and controls
101 lines (63 loc) · 1.9 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
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
// Given an array arr of positive integers sorted in a strictly increasing order, and an integer k.
// Return the kth positive integer that is missing from this array.
// Example 1:
// Input: arr = [2,3,4,7,11], k = 5
// Output: 9
// Explanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5th missing positive integer is 9.
// Example 2:
// Input: arr = [1,2,3,4], k = 2
// Output: 6
// Explanation: The missing positive integers are [5,6,7,...]. The 2nd missing positive integer is 6.
// My approach using set but not optimal class Solution {
public:
int findKthPositive(vector<int>& arr, int k) {
unordered_set<int> s(arr.begin(), arr.end());
int num = 1;
while (true) {
if (s.find(num) == s.end()) {
k--;
if (k == 0)
return num;
}
num++;
}
}
};
// ChatGPT approach
class Solution {
public:
int findKthPositive(vector<int>& arr, int k) {
int left = 0, right = arr.size() - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
int missing = arr[mid] - (mid + 1);
if (missing < k)
left = mid + 1;
else
right = mid - 1;
}
return left + k;
}
};
// Leetcode optimal solution
class Solution {
public:
int findKthPositive(vector<int>& nums, int k) {
int n=nums.size();
vector<int>ans(k);
int i=0,j=0;
int count=1;
while(j<k){
if(i<n && nums[i]==count){
count++;
i++;
}
else{
ans[j]=count;
j++;
count++;
}
}
return ans[j-1];
}
};