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 also be sorted in ascending order.
An integer a is closer to x than an integer b if:
1 | |a - x| < |b - x|, or |
Example 1:
1 | Input: arr = [1,2,3,4,5], k = 4, x = 3 |
Example 2:
1 | Input: arr = [1,2,3,4,5], k = 4, x = -1 |
Constraints:
1 | 1 <= k <= arr.length |
Solutions
The answer must be a continuous window; numbers are excluded from the left and right ends of the window, leaving k numbers at the end
1 | # O(n) time | O(1) space |