#C8446. K Closest Numbers
K Closest Numbers
K Closest Numbers
You are given an array of integers and two other integers k and x. Your task is to find the k closest numbers to x in the array.
The closeness of a number ai to x is determined by the absolute difference, i.e., \( |a_i - x| \). In case of a tie (i.e. two numbers have the same absolute difference), the smaller number should be considered closer. Finally, return the result sorted in ascending order.
Input Format: See below.
Output Format: See below.
inputFormat
The input is given from stdin and consists of four lines:
- The first line contains an integer n, the number of elements in the array.
- The second line contains n space-separated integers representing the array.
- The third line contains an integer k, the number of closest elements to find.
- The fourth line contains an integer x, the target number.
outputFormat
Print the k closest numbers to x in ascending order on a single line, separated by a single space, to stdout.
## sample5
1 2 3 4 5
4
3
1 2 3 4