Advertisement
7oSkaaa

Find K Closest Elements

Aug 10th, 2021
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.69 KB | None | 0 0
  1. #pragma GCC optimize("Ofast")
  2. static auto _ = [] () {ios_base::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);return 0;}();
  3.  
  4. class Solution {
  5. public:    
  6.     vector<int> findClosestElements(vector<int>& arr, int k, int x) {
  7.         int r = lower_bound(arr.begin(), arr.end(), x) - arr.begin();
  8.         int l = r - 1, idx = 0;
  9.         vector < int > res(k);
  10.         while(k--){
  11.             if(l < 0) res[idx++] = arr[r++];
  12.             else if(r >= arr.size()) res[idx++] = arr[l--];
  13.             else if(abs(arr[l] - x) <= abs(arr[r] - x)) res[idx++] = arr[l--];
  14.             else res[idx++] = arr[r++];
  15.         }
  16.         sort(res.begin(), res.end());
  17.         return res;
  18.     }
  19. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement