-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsmallestDistancePair.java
More file actions
40 lines (32 loc) · 1.24 KB
/
smallestDistancePair.java
File metadata and controls
40 lines (32 loc) · 1.24 KB
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
class Solution {
public int smallestDistancePair(int[] nums, int k) {
Arrays.sort(nums); // Step 1: Sort the array
int n = nums.length;
// Step 2: Set the binary search bounds
int left = 0; // Minimum possible distance
int right = nums[n - 1] - nums[0]; // Maximum possible distance
// Step 3: Binary search for the kth smallest distance
while (left < right) {
int mid = left + (right - left) / 2; // Midpoint distance
if (countPairs(nums, mid) < k) {
left = mid + 1; // Look for larger distances
} else {
right = mid; // Look for smaller distances
}
}
return left; // The kth smallest distance
}
// Helper function to count pairs with distance <= mid
private int countPairs(int[] nums, int mid) {
int count = 0;
int left = 0;
// Two-pointer technique
for (int right = 0; right < nums.length; right++) {
while (nums[right] - nums[left] > mid) {
left++; // Move left pointer to maintain the distance condition
}
count += right - left; // Count pairs (left, right)
}
return count;
}
}