Description

Given a sorted integer array arr, two integers k and x, return the k closest integers to x in the array. The result should be sorted in ascending order. An integer a is closer to x than b if |a - x| < |b - x|, or |a - x| == |b - x| and a < b.

Examples

Input:arr = [1,2,3,4,5], k = 4, x = 3
Output:[1,2,3,4]
Explanation:

4 closest elements to 3 are 1,2,3,4.

Input:arr = [1,2,3,4,5], k = 4, x = -1
Output:[1,2,3,4]
Explanation:

4 closest elements to -1 are 1,2,3,4.

Input:arr = [0,0,1,2,3,3,4,7,7,8], k = 3, x = 5
Output:[3,4,7]
Explanation:

The target x=5 is not in the array. The task requires find 3 closest elements. Distance from 5: |3-5|=2, |4-5|=1, |7-5|=2. Since 4 has the smallest distance (1), it's included. For elements with distance 2, there are 3 and 7. The requirement is 2 more elements, so taking both 3 and 7. The result [3,4,7] is sorted in ascending order.

Constraints

  • 1 ≤ k ≤ arr.length
  • 1 ≤ arr.length ≤ 10⁴
  • arr is sorted in ascending order.

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!