题目:
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
.
思路:
我们首先对nums进行排序,这样就可以得到distance的最小值left和最大值right了。然后二分查找:对于一个介于low和high之间的数mid,我们统计差值小于mid的一共有多少个,如果小于k,那么说明说明mid的取值偏小,所以修改low的值;否则修改high的值。这样不断迭代,最终当low > high的时候,low即为所求。
当然本题也可以用heap的思路:不断从所有pair中取出distance最小的pair,当取到第k个的时候,其差值即为所求。
代码:
class Solution {
public:
int smallestDistancePair(vector<int>& nums, int k) {
sort(nums.begin(), nums.end());
int n = nums.size(), low = 0, high = nums.back() - nums[0];
while (low <= high) {
int mid = (low + high) / 2, cnt = 0, j = 0;
for (int i = 0; i < n; ++i) {
while (j < n && nums[j] - nums[i] <= mid) {
++j;
}
cnt += j - i - 1;
}
if (cnt < k)
low = mid + 1;
else
high = mid - 1;
}
return low;
}
};