K Closest Elements in a Sorted Array
Problem statement
Given an integer array arr sorted in nondecreasing order, an integer k, and a target x, return the k values closest to x in ascending order.
A value a is closer than a value b when |a - x| < |b - x|. When the distances are equal, the smaller value is considered closer.
Function
findClosestElements(arr: int[], k: int, x: int) → int[]Examples
Example 1
arr = [-10,-4,-1,3,8,12]k = 4x = 2return = [-4,-1,3,8]Values -4 and 8 are equally distant from 2; the smaller value wins the boundary tie.
Example 2
arr = [2,4,6,8]k = 1x = 5return = [4]Values 4 and 6 are both one unit away, so the smaller value 4 is selected.
Example 3
arr = [5,6,7]k = 2x = 100return = [6,7]The target lies to the right of every array value, so the last two values are closest.
Constraints
1 <= arr.length <= 100000.1 <= k <= arr.length.arris sorted in nondecreasing order.-1000000000 <= arr[i], x <= 1000000000.