719. Find K-th Smallest Pair Distance #318
-
Topics: The distance of a pair of integers Given an integer array Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can use a combination of binary search and two-pointer technique. Here's a step-by-step approach to solving this problem: Approach:
Let's implement this solution in PHP: 719. Find K-th Smallest Pair Distance <?php
function countPairsWithDistanceLessThanOrEqualTo($nums, $mid) {
$count = 0;
$left = 0;
for ($right = 1; $right < count($nums); $right++) {
while ($nums[$right] - $nums[$left] > $mid) {
$left++;
}
$count += $right - $left;
}
return $count;
}
function smallestDistancePair($nums, $k) {
sort($nums);
$low = 0;
$high = $nums[count($nums) - 1] - $nums[0];
while ($low < $high) {
$mid = intval(($low + $high) / 2);
if (countPairsWithDistanceLessThanOrEqualTo($nums, $mid) < $k) {
$low = $mid + 1;
} else {
$high = $mid;
}
}
return $low;
}
// Example usage:
$nums = [1, 3, 1];
$k = 1;
echo smallestDistancePair($nums, $k); // Output: 0
?> Explanation:
This algorithm efficiently finds the |
Beta Was this translation helpful? Give feedback.
We can use a combination of binary search and two-pointer technique. Here's a step-by-step approach to solving this problem:
Approach:
Sort the Array: First, sort the array
nums
. Sorting helps in efficiently calculating the number of pairs with a distance less than or equal to a given value.Binary Search on Distance: Use binary search to find the
k
-th smallest distance. The search space for the distances ranges from0
(the smallest possible distance) tomax(nums) - min(nums)
(the largest possible distance).Count Pairs with Distance ≤ Mid: For each mid value in the binary search, count the number of pairs with a distance less than or equal to
mid
. This can be done efficiently using…