Loading content...
You are provided with a sorted integer array arr arranged in ascending order, along with two integer parameters k and x. Your objective is to identify and return the k integers from the array that are closest in value to x. The returned result must also be arranged in ascending order.
The proximity of an integer a to x compared to another integer b is determined by the following rules:
|a - x| is strictly less than |b - x|, OR|a - x| == |b - x|), but a is smaller than b (i.e., a < b)In essence, when two values are equidistant from the reference point x, the smaller value is considered closer and should be prioritized in the result.
arr = [1,2,3,4,5]
k = 4
x = 3[1,2,3,4]The values closest to 3 are 2, 3, 4, and 1 (in order of proximity). Since |2-3|=1, |4-3|=1, |1-3|=2, |5-3|=2, and we prefer smaller values when distances are equal, we select [1,2,3,4]. The result is returned in sorted order.
arr = [1,1,2,3,4,5]
k = 4
x = -1[1,1,2,3]Since x = -1 is to the left of all elements, the closest elements are simply the first k elements from the beginning of the array: [1,1,2,3].
arr = [1,3,5,7,9]
k = 2
x = 5[3,5]The value 5 is exactly in the array. The closest values are 5 itself (distance 0) and 3 (distance 2). Note that 7 also has distance 2, but 3 < 7, so 3 is preferred. Result: [3,5].
Constraints