Skip to content

Commit

Permalink
Add some code
Browse files Browse the repository at this point in the history
  • Loading branch information
codeAbinash committed Aug 14, 2024
1 parent 3b33e64 commit cffe83c
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions leetcode/problems/java/find-k-th-smallest-pair-distance.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@

import java.util.Arrays;

class Solution {
public int smallestDistancePair(int[] numbers, int k) {
Arrays.sort(numbers);
int minDist = 0;
int maxDistance = numbers[numbers.length - 1] - numbers[0];

while (minDist < maxDistance) {
int mid = minDist + (maxDistance - minDist) / 2;
int count = countPairsWithinDistance(numbers, mid);
if (count < k)
minDist = mid + 1;
else
maxDistance = mid;
}
return minDist;
}

private int countPairsWithinDistance(int[] numbers, int targetDistance) {
int count = 0;
int left = 0;
for (int right = 1; right < numbers.length; right++) {
while (numbers[right] - numbers[left] > targetDistance)
left++;
count += right - left;
}
return count;
}
}

0 comments on commit cffe83c

Please sign in to comment.