719. Find K-th Smallest Pair Distance

Posted ruruozhenhao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了719. Find K-th Smallest Pair Distance相关的知识,希望对你有一定的参考价值。

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.

 Approach #1: Brute Force.[Memory Limit Exceeded] 

class Solution {
public:
    int smallestDistancePair(vector<int>& nums, int k) {
        int len = nums.size();
        vector<int> temp;
        for (int i = 0; i < len; ++i) {
            for (int j = i+1; j < len; ++j) {
                int sub = abs(nums[i] - nums[j]);
                temp.push_back(sub);
            }
        }
        sort(temp.begin(), temp.end());
        return temp[k-1];
    }
};

  

Approach #2: Brute Force. [Bucter Sort]

class Solution {
public:
    int smallestDistancePair(vector<int>& nums, int k) {
        int len = nums.size();
        sort(nums.begin(), nums.end());
        int N = nums.back();
        vector<int> container(N+1, 0);
        for (int i = 0; i < len; ++i) {
            for (int j = i+1; j < len; ++j) {
                ++container[nums[j]-nums[i]];
            }
        }
        for (int i = 0; i <= N; ++i) {
            k -= container[i];
            if (k <= 0) return i;
        }
        return 0;
    }
};

Runtime: 580 ms, faster than 13.29% of C++ online submissions for Find K-th Smallest Pair Distance.

 

Approach #2: Binary Search + DP

class Solution {
public:
    int smallestDistancePair(vector<int>& nums, int k) {
        int len = nums.size();
        sort(nums.begin(), nums.end());
        int l = 0;
        int r = nums.back() - nums.front();
        while (l <= r) {
            int count = 0;
            int j = 0;
            int m = l + (r - l) / 2;
            for (int i = 0; i < len; ++i) {
                while (j < len && nums[j] - nums[i] <= m) j++;
                count += j - i - 1;
            }
            count >= k ? r = m - 1 : l = m + 1;
        }
        return l;
    }
};
Runtime: 16 ms, faster than 43.93% of C++ online submissions for Find K-th Smallest Pair Distance.

 

we can use a constant to instead dp array.

 

以上是关于719. Find K-th Smallest Pair Distance的主要内容,如果未能解决你的问题,请参考以下文章

武大OJ 574. K-th smallest

786. K-th Smallest Prime Fraction

LWC 72: 786. K-th Smallest Prime Fraction

Leetcode: K-th Smallest in Lexicographical Order

[LeetCode] K-th Smallest in Lexicographical Order 字典顺序的第K小数字

The 15th Chinese Northeast L. k-th Smallest Common Substring(广义SAM,对节点字典序排序)