Advertisement
nikunjsoni

658

May 18th, 2021
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.78 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     vector<int> findClosestElements(vector<int>& arr, int k, int x) {
  4.         int left=0, right=arr.size()-k;
  5.        
  6.         // Binary search the first val in range [0, n-k].
  7.         // Decide where to move the sliding window based on 4 conditions.
  8.         // Here leftmost bs is used since we want the leftmost starting point satisfying all conditions.
  9.         while(left<right){
  10.             int mid = (left+right)/2;
  11.             if(x-arr[mid] > arr[mid+k]-x)
  12.                 left = mid+1;
  13.             else
  14.                 right = mid;
  15.         }
  16.        
  17.         // Get the elements of sliding window in vector and return.
  18.         vector<int> ans;
  19.         for(int i=left; i<left+k; i++)
  20.             ans.push_back(arr[i]);
  21.         return ans;
  22.     }
  23. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement