Given a sorted integer array arr, two integers k and x, return the k closest integers to x in the array. The result should also be sorted in ascending order.
An integer a is closer to x than an integer b if:
|a - x| < |b - x|, or
|a - x| == |b - x| and a < b
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution { public: vector<int> findClosestElements(vector<int>& arr, int k, int x){ int r = lower_bound(begin(arr), end(arr), x) - begin(arr), l = r - 1; vector<int> res; while(k--) { if(l == -1) res.push_back(arr[r++]); elseif(r == arr.size()) res.push_back(arr[l--]); else { if(abs(arr[r] - x) < abs(arr[l] - x)) res.push_back(arr[r++]); else res.push_back(arr[l--]); } } sort(begin(res), end(res)); return res; } };