Skip to content

Commit ce35319

Browse files
add a solution for 1539
1 parent e331cad commit ce35319

File tree

2 files changed

+51
-5
lines changed

2 files changed

+51
-5
lines changed

Diff for: src/main/java/com/fishercoder/solutions/_1539.java

+32
Original file line numberDiff line numberDiff line change
@@ -64,4 +64,36 @@ public int findKthPositive(int[] arr, int k) {
6464
return result;
6565
}
6666
}
67+
68+
public static class Solution3 {
69+
/**
70+
* Use binary search:
71+
* use an array without missing integers to illustrate:
72+
* 1, 2, 3, 4, 5
73+
* 2, 3, 4, 7, 11
74+
* at index = 2, number of missing positive numbers: arr[index] - index - 1
75+
* <p>
76+
* Space: O(1)
77+
* Time: O(logn)
78+
* Credit: https://leetcode.com/problems/kth-missing-positive-number/editorial/
79+
*/
80+
public int findKthPositive(int[] arr, int k) {
81+
int left = 0;
82+
int right = arr.length - 1;
83+
while (left <= right) {
84+
int mid = left + (right - left) / 2;
85+
if (arr[mid] - mid - 1 < k) {
86+
left = mid + 1;
87+
} else {
88+
right = mid - 1;
89+
}
90+
}
91+
//when it exits the above while loop, left = right + 1;
92+
//the k-th missing number should be between arr[right] and arr[left]
93+
//the number of integers missing before arr[right] is arr[right] - right - 1;
94+
//so the number to return is:
95+
//arr[right] + k - (arr[right] - right - 1) = k + right + 1 = k + left;
96+
return left + k;
97+
}
98+
}
6799
}

Diff for: src/test/java/com/fishercoder/_1539Test.java

+19-5
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,22 @@
11
package com.fishercoder;
22

33
import com.fishercoder.solutions._1539;
4-
import org.junit.BeforeClass;
5-
import org.junit.Test;
4+
import org.junit.jupiter.api.BeforeEach;
5+
import org.junit.jupiter.api.Test;
66

7-
import static junit.framework.TestCase.assertEquals;
7+
import static org.junit.jupiter.api.Assertions.assertEquals;
88

99
public class _1539Test {
1010
private static _1539.Solution1 solution1;
1111
private static _1539.Solution2 solution2;
12+
private static _1539.Solution3 solution3;
1213
private static int[] arr;
1314

14-
@BeforeClass
15-
public static void setup() {
15+
@BeforeEach
16+
public void setup() {
1617
solution1 = new _1539.Solution1();
1718
solution2 = new _1539.Solution2();
19+
solution3 = new _1539.Solution3();
1820
}
1921

2022
@Test
@@ -41,4 +43,16 @@ public void test4() {
4143
assertEquals(6, solution2.findKthPositive(arr, 2));
4244
}
4345

46+
@Test
47+
public void test5() {
48+
arr = new int[]{2, 3, 4, 7, 11};
49+
assertEquals(9, solution3.findKthPositive(arr, 5));
50+
}
51+
52+
@Test
53+
public void test6() {
54+
arr = new int[]{1, 2, 3, 4};
55+
assertEquals(6, solution3.findKthPositive(arr, 2));
56+
}
57+
4458
}

0 commit comments

Comments
 (0)