Same Idea: Binary Search + two pointers

public List<Integer> findClosestElements(List<Integer> arr, int k, int x) {
int p = findInsertPos(arr,x);
//System.out.println(p);
List<Integer> res = new LinkedList<>();
int l = p - 1;
int r = p;
int count = 0;
while(l >= 0 && r < arr.size()&&count < k){
if(x-arr.get(l)>arr.get(r)-x){
count++;
r++;
}
else{
count++;
l--;
}
}
// System.out.println(l);
// System.out.println(r);
// System.out.println(count);
while(l >= 0&&count < k){
l--;
count++;
}
while(r < arr.size()&&count < k){
r++;
count++;
}
//System.out.println(l);
//System.out.println(r);
for(int i = l + 1;i < r;i++){
res.add(arr.get(i));
}
return res;
}
private int findInsertPos(List<Integer> arr,int x){
int left = 0;
int right = arr.size() - 1;
while(left <= right){
int mid = left + (right - left)/2;
if(arr.get(mid) < x){
left = mid + 1;
}
else{
right = mid - 1;
}
}
return left;
}
}