forked from KnowledgeCenterYoutube/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
1539_Kth_Missing_Positive_Number
65 lines (54 loc) · 1.35 KB
/
1539_Kth_Missing_Positive_Number
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
Leetcode 1539: Kth Missing Positive Number
Detailed video explanation:
====================================================
C++:
----
class Solution {
public:
int findKthPositive(vector<int>& arr, int k) {
int next_int = 1;
for(int a: arr){
if(a == next_int)
next_int++;
else{
int gap = a - next_int;
if(gap >= k) return next_int + k -1;
k -= gap;
next_int = a+1;
}
}
return next_int + k -1;
}
};
Java:
-----
class Solution {
public int findKthPositive(int[] arr, int k) {
int next_int = 1;
for(int a: arr){
if(a == next_int)
next_int++;
else{
int gap = a - next_int;
if(gap >= k) return next_int + k -1;
k -= gap;
next_int = a+1;
}
}
return next_int + k -1;
}
}
Python3:
--------
class Solution:
def findKthPositive(self, arr: List[int], k: int) -> int:
next_int = 1
for a in arr:
if a == next_int:
next_int += 1
else:
gap = a - next_int
if gap >= k: return next_int + k -1
k -= gap
next_int = a+1
return next_int + k -1