30:00
Given a sorted array, find the k closest integers to x. The result should also be sorted in ascending order.
1≤k≤arr.length1 \leq k \leq \text{arr.length}1≤k≤arr.length
1≤arr.length≤1041 \leq \text{arr.length} \leq 10^41≤arr.length≤104
arr is sorted in ascending order.
arr
−104≤arr[i],x≤104-10^4 \leq \text{arr}[i], x \leq 10^4−104≤arr[i],x≤104
Find 4 closest elements to 3. Binary search for window start in [0, 1]
1
2
3
4
5
Binary search for the left boundary of the k-element window. Compare distance from x to arr[mid] vs arr[mid+k] to decide which direction to search.