#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
int search(vector<int> arr,int n,int x){
int low=0,high=n-1;
while(low<=high){
int mid=low+(high-low)/2;
if(arr[mid]>x){
high=mid-1;
}
else if(arr[mid]<x){
low=mid+1;
}
else{
return mid;
}
}
return low;
}
vector<int> findClosestElements(vector<int>& arr, int k, int x) {
vector<int> ans;
int n=arr.size();
int i=search(arr,n,x);
int l=i-1,r=i;
while(k>0){
if(l<0 || (r<n && abs(arr[l]-x)>abs(arr[r]-x))){
r++;
}
else{
l--;
}
k--;
}
l++;
while(l<r){
ans.push_back(arr[l]);
l++;
}
return ans;
}
};
int main(){
Solution s;
vector<int> a={1,2,3,4,5};
int k=3,x=2;
vector<int> ans=s.findClosestElements(a,k,x);
for(auto i:ans){
cout<<i<<" ";
}cout<<endl;
return 0;
}
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter