add: 220615-CN
This commit is contained in:
parent
0591127d42
commit
9190e5ba1c
|
|
@ -0,0 +1,31 @@
|
|||
#include <vector>
|
||||
#include <algorithm>
|
||||
|
||||
/**
|
||||
* 719. Find K-th Smallest Pair Distance
|
||||
* The distance of a pair of integers a and b is defined as the absolute difference between a and b.
|
||||
* Given an integer array nums and an integer k, return the kth smallest distance among all the pairs nums[i] and nums[j] where 0 <= i < j < nums.length.
|
||||
*/
|
||||
|
||||
class Solution {
|
||||
public:
|
||||
static int smallestDistancePair(std::vector<int>& nums, int k) {
|
||||
const int n = nums.size();
|
||||
std::sort(nums.begin(), nums.end());
|
||||
int L = 0, R = nums.back();
|
||||
while (L < R) {
|
||||
int M = (L + R) >> 1;
|
||||
int i = 0, c = 0;
|
||||
for (int j = 0; j < n; ++j) {
|
||||
while (nums[j] - nums[i] > M)
|
||||
++i;
|
||||
c += j - i;
|
||||
}
|
||||
if (c >= k)
|
||||
R = M;
|
||||
else
|
||||
L = M + 1;
|
||||
}
|
||||
return L;
|
||||
}
|
||||
};
|
||||
|
|
@ -3,4 +3,4 @@ PROJECT(2206)
|
|||
|
||||
SET(CMAKE_CXX_STANDARD 23)
|
||||
|
||||
ADD_EXECUTABLE(2206 220615.cpp)
|
||||
ADD_EXECUTABLE(2206 220615-CN.cpp)
|
||||
|
|
|
|||
Loading…
Reference in New Issue