码迷,mamicode.com
首页 > 其他好文 > 详细

719. Find K-th Smallest Pair Distance

时间:2018-11-08 22:09:02      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:ble   ++i   bin   arc   int   sha   pos   vector   efi   

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

标签:ble   ++i   bin   arc   int   sha   pos   vector   efi   

原文地址:https://www.cnblogs.com/ruruozhenhao/p/9931935.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!