lurenaa的博客

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public:
int smallestDistancePair(vector<int>& nums, int k) {
sort(nums.begin(), nums.end());
int left = 0,
right = nums.back() - nums.front(), mi;
while(left < right) {
mi = left + (right - left) / 2;
int count = 0;
int start = 0;
for(int i = 0;i < nums.size(); ++i) {
while(nums[i] - nums[start] > mi) {
++start;
}
count += i - start;
}
if(count < k) { //如果小于K个
left = mi + 1;
} else {
right = mi;
}
}
return left;
}
};

Accepted

19/19 cases passed (16 ms)

Your runtime beats 72.62 % of cpp submissions

Your memory usage beats 8.33 % of cpp submissions (12.4 MB)