Skip to content

Commit 67c2a55

Browse files
committed
Updates leetcode/binary-search/719-find-k-th-smallest-pair-distance.md
Auto commit by GitBook Editor
1 parent 21daa34 commit 67c2a55

File tree

1 file changed

+31
-2
lines changed

1 file changed

+31
-2
lines changed

leetcode/binary-search/719-find-k-th-smallest-pair-distance.md

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ Here are all the pairs:
1919
Then the 1st smallest distance pair is (1,1), and its distance is 0.
2020
```
2121

22-
**Note:
22+
**Note:
2323
**
2424

2525
1. 2 <= len\(nums\) <= 10000.
@@ -41,9 +41,11 @@ Then the 1st smallest distance pair is (1,1), and its distance is 0.
4141
5. Space complexity O\(n\)
4242
3. Binary Search
4343
1. Since all numbers are non-negative, the kth distance must be in between \[0, max - min\], lo and hi respectively
44-
2. We perform binary search on this range until lo and hi merge, and we narrow our search using a separate function count\(mi\), where count\(mi\) return numbers of distances smaller than or equal to mi
44+
2. We perform binary search on this range until lo and hi merge, and we narrow our search using a separate function count\(nums, mi\), where count\(nums, mi\) return numbers of distances <= mi
4545
3. If count\(mi\) is smaller than k, we have to set lo = mi + 1
4646
4. Else hi = mi
47+
5. The count\(nums, mi\) can be efficiently implemented using two pointers \(sliding window\) method
48+
6. Time complexity O\(nlogn + n^2logw\), where w = max - min
4749

4850
### Solution
4951

@@ -90,6 +92,33 @@ class Solution {
9092
}
9193
```
9294

95+
```java
96+
class Solution {
97+
public int smallestDistancePair(int[] nums, int k) {
98+
Arrays.sort(nums);
99+
int lo = 0, hi = nums[nums.length - 1] - nums[0];
100+
while (lo != hi) {
101+
int mi = lo + (hi - lo) / 2;
102+
if (count(nums, mi) < k) lo = mi + 1;
103+
else hi = mi;
104+
}
105+
return lo;
106+
}
107+
108+
private int count(int[] nums, int d) {
109+
int right = 1;
110+
int count = 0;
111+
while (right < nums.length) {
112+
int left = 0;
113+
while (nums[right] - nums[left] > d) left++;
114+
count += right - left;
115+
right++;
116+
}
117+
return count;
118+
}
119+
}
120+
```
121+
93122
### Additional {#additional}
94123

95124

0 commit comments

Comments
 (0)