Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #pragma GCC optimize("Ofast")
- static auto _ = [] () {ios_base::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);return 0;}();
- class Solution {
- public:
- vector<int> findClosestElements(vector<int>& arr, int k, int x) {
- int r = lower_bound(arr.begin(), arr.end(), x) - arr.begin();
- int l = r - 1, idx = 0;
- vector < int > res(k);
- while(k--){
- if(l < 0) res[idx++] = arr[r++];
- else if(r >= arr.size()) res[idx++] = arr[l--];
- else if(abs(arr[l] - x) <= abs(arr[r] - x)) res[idx++] = arr[l--];
- else res[idx++] = arr[r++];
- }
- sort(res.begin(), res.end());
- return res;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement