[Leetcode] 719. Find K-th Smallest Pair Distance 解题报告

这篇博客详细介绍了LeetCode 719题的解题报告,讨论如何找到数组中第k小的配对距离。作者提出两种解决方案:一种是使用排序结合二分查找法,另一种是利用堆数据结构。通过排序找到距离的最小值和最大值,然后进行二分查找,统计小于目标距离的配对数量。此外,还提到可以用堆来不断获取最小距离的配对,直到找到第k个配对。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

Given an integer array, return the k-th smallest distance among all the pairs. The distance of a pair (A, B) is defined as the absolute difference between A and B.

Example 1:

Input:
nums = [1,3,1]
k = 1
Output: 0 
Explanation:
Here are all the pairs:
(1,3) -> 2
(1,1) -> 0
(3,1) -> 2
Then the 1st smallest distance pair is (1,1), and its distance is 0.

Note:

  1. 2 <= len(nums) <= 10000.
  2. 0 <= nums[i] < 1000000.
  3. 1 <= k <= len(nums) * (len(nums) - 1) / 2.

思路

我们首先对nums进行排序,这样就可以得到distance的最小值left和最大值right了。然后二分查找:对于一个介于low和high之间的数mid,我们统计差值小于mid的一共有多少个,如果小于k,那么说明说明mid的取值偏小,所以修改low的值;否则修改high的值。这样不断迭代,最终当low > high的时候,low即为所求。

当然本题也可以用heap的思路:不断从所有pair中取出distance最小的pair,当取到第k个的时候,其差值即为所求。

代码

class Solution {
public:
    int smallestDistancePair(vector<int>& nums, int k) {
        sort(nums.begin(), nums.end());
        int n = nums.size(), low = 0, high = nums.back() - nums[0];
        while (low <= high) {
            int mid = (low + high) / 2, cnt = 0, j = 0;
            for (int i = 0; i < n; ++i) {
                while (j < n && nums[j] - nums[i] <= mid) {
                    ++j;
                }
                cnt += j - i - 1;
            }
            if (cnt < k) 
                low = mid + 1;
            else
                high = mid - 1;
        }
        return low;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值