1.Description
Given a sorted array, and two integers k and x. Find the k closest elements to x in the array.
2. Solution
Use binary search to find the closest element to x in the array,
and find other k-1 elements from the two sides of the closest element.
3. Code
vector<int> findClosestElements(vector<int>& arr, int k, int x) {
int n = arr.size();
vector<int>ans;
if(k==0) return ans;
int l=0,r=n-1;
int id = -1;
while(l<r){
int mid = l+(r-l)/2;
if(arr[mid]>=x)
r = mid;
else
l=mid+1;
}
id = l;
if(l>0 && x - arr[l-1]< arr[l] - x)
id = l-1;
ans.push_back(arr[id]);
k--;
int i = id-1,j=id+1;
while(k--){
if(i>=0&&j<n){
if(abs(arr[i]-x)<=abs(arr[j]-x)){
ans.push_back(arr[i]);
i--;
}
else{
ans.push_back(arr[j]);
j++;
}
}
else if(i>=0){
ans.push_back(arr[i]);
i--;
}
else{
ans.push_back(arr[j]);
j++;
}
}
sort(ans.begin(),ans.end());
return ans;
}