leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0658.cpp (704B)


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