您的位置:首页 > 大数据 > 人工智能

Leet 4000 Code Find K-th Smallest Pair Distance

2017-12-04 16:52 337 查看
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.

题意为给定一个数组,计算任意两个数之间的距离,返回所有距离中第k小的距离。最初的做法是建立一个vector存储所有距离,再将距离排序输出第k个值。运行时超时。后来改进了一下,建立大小为N的容器,运行通过了但运行时间很长:

class Solution {
public:
int smallestDistancePair(vector<int>& nums, int k) {
int N = 1000000;
vector<int> res(N, 0);

for(int i=0; i<nums.size(); i++)
{
for(int j=i+1; j<nums.size(); j++)
{
res[abs(nums[i] - nums[j])]++;
}
}

for(int i=0; i<N; i++)
{
if(res[i] >= k) return i;
k -= res[i];
}
return 0;
}
};


看了提示说可以用二元搜索,又参照了其他人的做法,恍然大悟。cnt中存储所有差小于mid的个数,再将cnt与k相比较,若cnt小于k,则提高下限;否则,降低上限。用二元搜素解决该问题,确实很巧妙。

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


另:现在做题还没有形成一个好的思维方式,对大规模数据的处理以及排序方面接触较少,有待加强练习。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode