![元宝DeepSeek深度思考 LeetCode 719.找出第K小的数对距离 public int smallestDistancePair(int[] nums, int k)](http://pic.xiahunao.cn/yaotu/元宝DeepSeek深度思考 LeetCode 719.找出第K小的数对距离 public int smallestDistancePair(int[] nums, int k))
这个问题可以通过排序数组然后使用二分查找结合双指针来解决。首先对数组排序然后在距离的可能范围 [0, max(nums)-min(nums)] 内进行二分查找。对于每个猜测的距离 mid通过双指针统计距离小于等于 mid 的数对数量。如果数量大于等于 k则答案在左半部分否则在右半部分。以下是 Java 代码实现import java.util.Arrays;class Solution {public int smallestDistancePair(int[] nums, int k) {Arrays.sort(nums);int n nums.length;int left 0;int right nums[n - 1] - nums[0];while (left right) { int mid left (right - left) / 2; int count countPairs(nums, mid); if (count k) { right mid; } else { left mid 1; } } return left; } private int countPairs(int[] nums, int threshold) { int count 0; int i 0; for (int j 0; j nums.length; j) { while (nums[j] - nums[i] threshold) { i; } count j - i; } return count; }}时间复杂度O(n log n n log D)其中 D 是最大距离。空间复杂度O(1)。