-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1539-Kth_Missing_Positive_Number.cpp
More file actions
98 lines (89 loc) · 2.42 KB
/
1539-Kth_Missing_Positive_Number.cpp
File metadata and controls
98 lines (89 loc) · 2.42 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
/*******************************************************************************
* 1539-Kth_Missing_Positive_Number.cpp
* Billy.Ljm
* 06 Mar 2023
*
* =======
* Problem
* =======
* https://leetcode.com/problems/kth-missing-positive-number/
* 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
*
* ===========
* My Approach
* ===========
* We can iterate every integer, until we reach the desired missing integer k.
* Or, we can iterate through the input array, and use maths to calculate the
* all the missing integers b/w adjacent elements in one fell swoop. I'll
* implement the latter.
******************************************************************************/
#include <iostream>
#include <vector>
class Solution {
public:
/**
* Finds the k-th positive integer that is missing from a sorted array
*
* @param arr sorted array to find missing integers in
* @param k number of missing positive integers to ignore
*
* @return the k-th missing positive integer
*/
int findKthPositive(std::vector<int>& arr, int k) {
// process first interval [0, arr[0]]
int nmiss = arr[0] - 1; // num missing integers b/w adjacent values
if (nmiss < k) { // subtract any missing
k -= nmiss;
}
else { // k is before start of array
return k;
}
for (int i = 1; i < arr.size(); ++i) {
nmiss = arr[i] - arr[i - 1] - 1;
if (nmiss == 0) { // no missing integers, dont do anything
continue;
}
else if (nmiss < k) { // nearer to k, but haven't reached
k -= nmiss;
}
else { // reached k
return arr[i-1] + k;
}
}
// k is beyond end of arr
return arr.back() + k;
}
};
/**
* Print function for vector
*/
template <typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
os << "[";
for (int i = 0; i < v.size(); ++i) {
os << v[i] << ",";
}
os << "\b]";
return os;
}
/**
* Test cases
*/
int main(void) {
Solution sol;
std::vector<int> arr;
//test case 1
arr = { 2, 3, 4, 7, 11 };
std::cout << "findKthPositive(" << arr << ",5) = " <<
sol.findKthPositive(arr, 5) << std::endl;
//test case 2
arr = { 1, 2, 3, 4 };
std::cout << "findKthPositive(" << arr << ",2) = " <<
sol.findKthPositive(arr, 2) << std::endl;
//test case 2
arr = { 2 };
std::cout << "findKthPositive(" << arr << ",1) = " <<
sol.findKthPositive(arr, 1) << std::endl;
}