Problem · Array
Find K Closest Elements in a Sorted Array
Learn this problemProblem statement
Given a sorted integer array arr, an integer k, and a target x, return the k closest values to x in ascending order.
A value a is closer than b when |a - x| < |b - x|. For equal distances, the smaller value is closer.
Function
findClosestElements(arr: int[], k: int, x: int) → int[]Examples
Example 1
arr = [1,2,3,4,5]k = 4x = 3return = [1,2,3,4]The four smallest distances belong to 1, 2, 3, and 4.
Example 2
arr = [1,2,3,4,5]k = 4x = -1return = [1,2,3,4]The target lies left of the array, so the first four values are closest.
Constraints
arris non-empty and sorted in nondecreasing order.1 <= k <= arr.length.- All values and
xare signed integers.