Heaps Top K
410. Find K Closest Elements
You are given an array of integers arr, sorted in non-decreasing order, and two integers k and x. Return
the k elements of arr that are closest to x, sorted in increasing order.
An element a is closer to x than an element b when |a - x| < |b - x|. When the two are equally far
from x, the smaller one counts as closer.
A value can appear in arr more than once. Each copy is a separate element, so the answer can hold the same
value more than once.
Example 1
Input: arr = [-6, -2, 1, 3, 3, 8, 12], k = 5, x = 5
[-2,1,3,3,8]Explanation: The distances to 5 are 11, 7, 4, 2, 2, 3 and 7. The four closest elements are 3, 3, 8 and 1. For the fifth place, −2 and 12 are both 7 away, and the smaller one wins.
Example 2
Input: arr = [-10, -7, -3, 0, 2], k = 3, x = 9
[-3,0,2]Explanation: Every element is below 9, so the closest three are the three largest.
Example 3
Input: arr = [4, 4, 4, 6], k = 2, x = 5
[4,4]Explanation: Every element is 1 away from 5. The smaller value wins each tie, so the answer is two of the 4s.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ k ≤ arr.length ≤ 105-109 ≤ arr[i] ≤ 109arr[i] ≤ arr[i + 1](non-decreasing)-109 ≤ x ≤ 109
Clarifying questions
What you would ask an interviewer before writing any code.