You are given a sorted array of integers nums, an integer k, and an integer target.
Return the k values from nums that are closest to target, sorted in ascending order.
A value a is closer to target than a value b if abs(a - target) < abs(b - target), or if the two distances are equal and a < b.
Examples
Example 1
Input: nums = [1,2,3,4,5], k = 4, target = 3
Output: [1,2,3,4]
Explanation: The distances to 3 are 2, 1, 0, 1 and 2. The four smallest distances belong to 3, 2, 4 and 1 (1 is chosen over 5 because they tie on distance and 1 is smaller). Sorted ascending, that is [1,2,3,4].
Example 2
Input: nums = [1,1,2,3,4,5], k = 4, target = -1
Output: [1,1,2,3]
Explanation: The distances to -1 are 2, 2, 3, 4, 5 and 6. The four smallest distances belong to both 1s, then 2, then 3. Sorted ascending, that is [1,1,2,3].
Constraints
1≤k≤nums.length
1≤nums.length≤104
nums is sorted in ascending order.
−104≤nums[i], target≤104
Loading editor...
Run checks the sample cases; Submit runs every case.
Samples 2
Custom 0
passedwrong answertime limiterrorran, no expected valuenot run