Leetcode 719. Find K-th Smallest Pair Distance (binary search)

本文介绍了一种寻找数组中第K小的距离对的算法。首先通过暴力枚举所有可能的数对,利用计数排序减少排序时间。接着采用二分搜索距离,并通过双指针判断是否为第K小的距离。

Brute force

First, it's easy to find out a brute force solution:

  • First, enumerate all the pairs nums[i] and nums[j], the total number is \(O(n^2)\)
  • Second, we need to find out the Kth distance, to reduce the sorting time and because of 0 <= nums[i] < 1000000, so counting sort can be a good solution.

The time complexity of brute force solution is \(O(n^2)\).

We just binary search the distance ans, and judge if ans can be the Kth distance.
The time complexity of binary search distance ans is \(O(max(a_i))\).
Then we need to find out a method to judge whether ans is the Kth distance, the method is like two pointers, the cost time of this step is \(O(n)\). You can see the code below.

Code

class Solution {
public:
    bool judgeMore(const vector<int>& nums, int mid, int k) {
        int cnt = 0, j = 0;
        for (int i = 0; i < nums.size(); ++i) {
            while (j < nums.size() && nums[j] - nums[i] <= mid) { ++j; }
            cnt += j - i - 1;
            if (cnt >= k) return true;
        }
        return cnt >= k;
    }
    
    int smallestDistancePair(vector<int>& nums, int k) {
        sort(nums.begin(), nums.end());
        int l = 0, r = nums.back() - nums[0], mid = 0, ans = r;
        while (l <= r) {
            mid = l + (r - l) / 2;
            // mid is too big or may equal
            if (judgeMore(nums, mid, k)) {
                r = mid - 1;
                ans = mid;
            } else {
                l = mid + 1;
            }
        }
        return ans;
    }
};

转载于:https://www.cnblogs.com/caesium/p/7755018.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值