Advertisement
nikunjsoni

719

May 18th, 2021
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.75 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int smallestDistancePair(vector<int>& nums, int k) {
  4.         // Sort the array.
  5.         sort(nums.begin(), nums.end());
  6.        
  7.         int n = nums.size();
  8.         int l=0, r=nums[n-1]-nums[0];
  9.        
  10.         // Leftmost binary search.
  11.         while(l<r){
  12.             int count = 0;
  13.             int mid = (l+r)/2;
  14.            
  15.             // Count pairs with difference less-equal to mid.
  16.             for(int left=0, right=0; right<n; right++){
  17.                 while(nums[right]-nums[left] > mid)
  18.                     left++;
  19.                 count += right-left;
  20.             }
  21.             if(count < k)
  22.                 l = mid+1;
  23.             else
  24.                 r = mid;
  25.         }
  26.         return l;
  27.     }
  28. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement