Brute force
First, it's easy to find out a brute force solution:
- First, enumerate all the pairs nums[i] and nums[j], the total number is \(O(n^2)\)
- Second, we need to find out the Kth distance, to reduce the sorting time and because of
0 <= nums[i] < 1000000
, so counting sort can be a good solution.
The time complexity of brute force solution is \(O(n^2)\).
Binary search
We just binary search the distance ans
, and judge if ans
can be the Kth distance.
The time complexity of binary search distance ans
is \(O(max(a_i))\).
Then we need to find out a method to judge whether ans
is the Kth distance, the method is like two pointers, the cost time of this step is \(O(n)\). You can see the code below.
Code
class Solution {
public:
bool judgeMore(const vector<int>& nums, int mid, int k) {
int cnt = 0, j = 0;
for (int i = 0; i < nums.size(); ++i) {
while (j < nums.size() && nums[j] - nums[i] <= mid) { ++j; }
cnt += j - i - 1;
if (cnt >= k) return true;
}
return cnt >= k;
}
int smallestDistancePair(vector<int>& nums, int k) {
sort(nums.begin(), nums.end());
int l = 0, r = nums.back() - nums[0], mid = 0, ans = r;
while (l <= r) {
mid = l + (r - l) / 2;
// mid is too big or may equal
if (judgeMore(nums, mid, k)) {
r = mid - 1;
ans = mid;
} else {
l = mid + 1;
}
}
return ans;
}
};