From cffe83c341ddd294c8423fb3e54abc6bd35f8591 Mon Sep 17 00:00:00 2001 From: Abinash Karmakar Date: Wed, 14 Aug 2024 21:09:18 +0530 Subject: [PATCH] Add some code --- .../find-k-th-smallest-pair-distance.java | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 leetcode/problems/java/find-k-th-smallest-pair-distance.java diff --git a/leetcode/problems/java/find-k-th-smallest-pair-distance.java b/leetcode/problems/java/find-k-th-smallest-pair-distance.java new file mode 100644 index 0000000..59f278f --- /dev/null +++ b/leetcode/problems/java/find-k-th-smallest-pair-distance.java @@ -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; + } +} \ No newline at end of file