【LeetCode 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:

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

思路

思路一:桶排序,key是距离,value是距离的出现次数。遍历所有可能的距离,从小到大,k-当前距离的出现次数,k<=0时,当前距离为第k小。
思路二:二分,left 和 right为距离的最小最大值,遍历数组,求出小于当前距离 mid 的个数cnt,if cnt < k,left = mid + 1; else right = mid - 1;

代码

代码一:

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

代码二:

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

你可能感兴趣的:(LeetCode,二分)