Problem 365
Find K Closest Elements
Medium · 20 pts · Array, Binary Search, Two Pointers, Sorting
Problem
Given a sorted array, an integer K and a target X, find the K elements closest to X. Element a is closer than element b if |a - X| < |b - X|, or if the distances are equal and a < b (the smaller value wins a tie). Print the K chosen elements in ascending order. Because the array is sorted, the answer is always a contiguous block, which you can find with binary search or two pointers.
Input
First line: N, K and X. Second line: N integers in non-decreasing order.
Output
Print the K closest elements in ascending order, separated by spaces.
Constraints
1 <= K <= N <= 100000; -10000 <= A[i], X <= 10000
Example input
5 4 3 1 2 3 4 5
Example output
1 2 3 4
Explanation
With K = 4 and X = 3 in 1 2 3 4 5, the distances to 3 are 2 1 0 1 2. The four closest are 1, 2, 3 and 4 (1 beats 5 in the tie at distance 2).