Find K-th Smallest Pair Distance LeetCode solution in Java
1class Solution {2public int smallestDistancePair(int[] nums, int k) {3Arrays.sort(nums);4int low = 0, high = nums[nums.length - 1] - nums[0];56while (low <= high) {7int mid = low + (high - low) / 2;8if (noOfDistancesLessThan(mid, nums) >= k) high = mid - 1;9else low = mid + 1;10}11return low;12}1314private int noOfDistancesLessThan(int dist, int[] nums) {15int count = 0, i = 0, j = 0;16while (i < nums.length) {17while (j < nums.length && nums[j] - nums[i] <= dist) { // sliding window18j++;19}20count += j - i - 1;21i++;22}23return count;24}25}