Closed congr closed 5 years ago
Bin search should be modified, NLogN
class Solution {
public List<Integer> findClosestElements(int[] arr, int k, int x) {
List<Integer> list = new ArrayList();
int s = 0, e = arr.length-1;
while(e - s >= k) { // !!! >=
if (Math.abs(arr[s]-x) > Math.abs(arr[e]-x)) s++; // !!!
else e--; // !!!
}
for(int i = s; i <= e; i++) list.add(arr[i]);
return list;
}
}
https://leetcode.com/problems/find-k-closest-elements/