Enumerate
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| class Solution { public int findKthPositive(int[] arr, int k) { int x = 1; for (int num : arr) { while (x != num) { if (--k == 0) { return x; } x++; } x++; }
return x + k - 1; } }
|
Binary Search
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| class Solution { public int findKthPositive(int[] arr, int k) {
int i = 0, j = arr.length - 1;
while (i <= j) { int midIndex = (i + j) >>> 1; int expectedValue = midIndex + 1;
int missCount = arr[midIndex] - expectedValue; if (missCount < k) { i = midIndex + 1; } else { j = midIndex - 1; } }
return j + 1 + k; } }
|
References
1539. Kth Missing Positive Number