You are given an integer array arr sorted in non-decreasing order, a count k and a target value x. Pick the k values from arr that lie nearest to x, and return them sorted from smallest to largest.
Nearness is measured by distance to x. When two values are equally far from x, the smaller value counts as nearer. That is, a beats b when |a - x| < |b - x|, or when |a - x| == |b - x| and a < b. With this rule the chosen values, and so the answer, are always the same.
A value that appears several times in arr is several separate candidates.
5 is 1 away from 6, so it goes in first. 4 and 8 are both 2 away, and the tie goes to the smaller value, 4.
x is above every value, so the answer is the top 3: 9 (distance 1), 7 (3) and 0 (10).
All three copies of 3 sit at distance 0. For the fourth pick, 1 (distance 2) is nearer than 6 (distance 3).
Constraints
1 <= k <= arr.length <= 10⁴arr is sorted in non-decreasing order.-10⁴ <= arr[i] <= 10⁴-10⁴ <= x <= 10⁴Because arr is sorted, the k nearest values always sit side by side: the answer is a window of k neighbours. The only question is where that window starts.