forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_1539.java
67 lines (64 loc) · 1.78 KB
/
_1539.java
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
package com.fishercoder.solutions;
import java.util.HashSet;
import java.util.Set;
public class _1539 {
public static class Solution1 {
/**
* Space: O(n)
* Time: O(n)
*/
public int findKthPositive(int[] arr, int k) {
Set<Integer> set = new HashSet<>();
int max = 0;
for (int i : arr) {
set.add(i);
max = Math.max(max, i);
}
int missed = 0;
for (int i = 1; i <= max; i++) {
if (!set.contains(i)) {
missed++;
}
if (missed == k) {
return i;
}
}
while (missed++ < k) {
max++;
}
return max;
}
}
public static class Solution2 {
/**
* Space: O(1)
* Time: O(n)
*/
public int findKthPositive(int[] arr, int k) {
int missed = 0;
for (int i = 0; i < arr.length; i++) {
if (i == 0) {
missed += arr[0] - 1;
if (missed >= k) {
return k;
}
} else {
missed += arr[i] - arr[i - 1] - 1;
if (missed >= k) {
missed -= arr[i] - arr[i - 1] - 1;
int result = arr[i - 1];
while (missed++ < k) {
result++;
}
return result;
}
}
}
int result = arr[arr.length - 1];
while (missed++ < k) {
result++;
}
return result;
}
}
}