658. Find K Closest Elements
Practice Find K Closest Elements for free on NudgeCode: Medium, Sliding Window pattern. Write it in Python or JavaScript, run the tests in your browser, and ask for a hint when you are stuck.
Given a sorted array arr, return the k values closest to x, sorted in ascending order.
a is closer than b when |a - x| < |b - x|, or when the distances are equal and a < b.
Example
arr = [1,2,3,4,5], k = 4, x = 3 -> [1,2,3,4]
arr = [1,1,2,3,4,5], k = 4, x = -1 -> [1,1,2,3]
Constraints
- 1 <= k <= arr.length <= 10^4
arris sorted in ascending order- -10^4 <= arr[i], x <= 10^4