0719.cpp (715B)
1 class Solution { 2 int count(const vector<int> &nums, int tgt) const { 3 int res = 0; 4 5 for (int l = 0, r = 1; r < size(nums); r++) { 6 while (nums[r] - nums[l] > tgt) 7 l++; 8 res += r - l; 9 } 10 11 return res; 12 } 13 14 public: 15 int smallestDistancePair(vector<int> &nums, int k) const { 16 sort(begin(nums), end(nums)); 17 18 int low = 0, high = nums.back() - nums.front(); 19 while (low < high) { 20 const int mid = low + (high - low) / 2; 21 const int cnt = count(nums, mid); 22 23 if (cnt < k) 24 low = mid + 1; 25 else 26 high = mid; 27 } 28 29 return low; 30 } 31 };