0658.cpp (704B)
1 class Solution { 2 public: 3 vector<int> findClosestElements(const vector<int> &arr, int k, int x) const { 4 const int n = size(arr); 5 6 const auto mid = upper_bound(begin(arr), end(arr), x); 7 if (mid == end(arr)) return vector(begin(arr) + n - k, end(arr)); 8 9 int j = distance(begin(arr), mid), i = j - 1; 10 int a = 0, b = k - 1; 11 vector<int> res(k); 12 13 while (a <= b) { 14 if (j < n && (i < 0 || x - arr[i] > arr[j] - x)) 15 res[b--] = arr[j++]; 16 else 17 res[a++] = arr[i--]; 18 } 19 20 reverse(begin(res), begin(res) + a); 21 reverse(begin(res) + b + 1, end(res)); 22 23 return res; 24 } 25 };