-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution719.cs
54 lines (45 loc) · 1.33 KB
/
Solution719.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
using System.Text;
namespace LeetCode.Solutions;
public class Solution719
{
/// <summary>
/// 719. Find K-th Smallest Pair Distance - Hard
/// <a href="https://leetcode.com/problems/find-k-th-smallest-pair-distance">See the problem</a>
/// </summary>
public int SmallestDistancePair(int[] nums, int k)
{
Array.Sort(nums); // Step 1: Sort the array
int left = 0, right = nums[nums.Length - 1] - nums[0];
// Step 2: Binary search on distance
while (left < right)
{
var mid = left + (right - left) / 2;
// Step 3: Count pairs with distance <= mid
var count = CountPairs(nums, mid);
if (count >= k)
{
right = mid; // Try for a smaller distance
}
else
{
left = mid + 1; // Try for a larger distance
}
}
return left;
}
// Helper function to count pairs with distance <= maxDist
private int CountPairs(int[] nums, int maxDist)
{
var count = 0;
var j = 0;
for (var i = 0; i < nums.Length; i++)
{
while (j < nums.Length && nums[j] - nums[i] <= maxDist)
{
j++;
}
count += j - i - 1;
}
return count;
}
}