658. Find K Closest Elements
Last updated
Last updated
/**
* Time complexity :
* Space complexity :
*/
class Solution {
public List<Integer> findClosestElements(int[] arr, int k, int x) {
if(arr == null || arr.length < k) {
return List.of();
}
int low = 0, high = arr.length-k;
while(low < high) {
int mid = low + (high-low)/2;
if(x-arr[mid] > arr[mid+k]-x) {
low = mid + 1;
} else {
high = mid;
}
}
List<Integer> result = new ArrayList();
for(int i = low; i < low+k; i++) {
result.add(arr[i]);
}
return result;
}
}