719. Find K-th Smallest Pair Distance #318
Replies: 1 comment
-
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.
-
Topics:
Array
,Two Pointers
,Binary Search
,Sorting
The distance of a pair of integers
a
andb
is defined as the absolute difference betweena
andb
.Given an integer array
nums
and an integerk
, return thekth
smallest distance among all the pairsnums[i]
andnums[j]
where0 <= i < j < nums.length
.Example 1:
(1,3) -> 2
(1,1) -> 0
(3,1) -> 2
Then the 1st smallest distance pair is (1,1), and its distance is 0.
Example 2:
Example 3:
Constraints:
n == nums.length
2 <= n <= 104
0 <= nums[i] <= 106
1 <= k <= n * (n - 1) / 2
Hint:
Beta Was this translation helpful? Give feedback.
All reactions