0719. 找出第 K 小的距离对 #174
Replies: 1 comment
-
c++ class Solution {
public:
int smallestDistancePair(vector<int>& nums, int k) {
int n = nums.size();
sort(nums.begin(), nums.end());
int left = 0, right = nums.back() - nums.front();
while (left <= right) {
int mid = left + ((right - left) >> 1);
int j = 0;
int cnt = 0;
for (int i = 0; i < n; i++) {
while (j < n && nums[j] - nums[i] <= mid) {
j++;
}
cnt += (j - i - 1);
}
if (cnt < k) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return left;
}
}; |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
0719. 找出第 K 小的距离对
https://algo.itcharge.cn/Solutions/0700-0799/find-k-th-smallest-pair-distance/
Beta Was this translation helpful? Give feedback.
All reactions