Skip to content

Commit 3aaf828

Browse files
committed
Add Modified Binary Search/719_Find_K-th_Smallest_Pair_Distance.java
1 parent e0cace7 commit 3aaf828

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
class Solution {
2+
public int smallestDistancePair(int[] nums, int k) {
3+
Arrays.sort(nums);
4+
int low = 0, high = nums[nums.length - 1] - nums[0];
5+
6+
while (low < high) {
7+
int mid = low + (high - low) / 2;
8+
9+
int count = smallestDistancePairHelper(nums, mid);
10+
if (count < k) {
11+
low = mid + 1;
12+
} else {
13+
high = mid;
14+
}
15+
}
16+
17+
return low;
18+
}
19+
20+
private int smallestDistancePairHelper(int[] nums, int maxValue) {
21+
int left = 0, right = 0, count = 0;
22+
23+
while (right < nums.length) {
24+
while (left < right && nums[right] - nums[left] > maxValue) {
25+
++left;
26+
}
27+
28+
count += right - left;
29+
++right;
30+
}
31+
32+
return count;
33+
}
34+
}

0 commit comments

Comments
 (0)