1346. Nearest K to a Value
A thermostat stores past room temperatures in the unsorted array nums, and wants the k readings that are closest to the target temperature x. Rank every reading by the pair (|v - x|, v): a smaller distance is better, and when two readings are equally far from x the smaller value is better. Duplicate readings are separate entries and may be chosen several times.
Return the k best readings as an array sorted in ascending order. Compute |v - x| in 64-bit arithmetic, since v - x can exceed 32 bits. Sorting everything costs O(n log n). The intended solution selects the best k with quickselect on the ranking key in expected O(n) time and then sorts only those k values.
Example 1
- Input:
- nums = [10,2,14,3,6], k = 2, x = 5
- Output:
- [3,6]
- Explanation:
The distances to 5 are 5, 3, 9, 2 and 1, so the two closest values are 6 and 3, returned in ascending order.
Example 2
- Input:
- nums = [4,6,5], k = 2, x = 5
- Output:
- [4,5]
- Explanation:
The value 5 is closest, and 4 and 6 tie on distance 1, so the smaller value 4 wins.
Example 3
- Input:
- nums = [7,7,7,1], k = 3, x = 100
- Output:
- [7,7,7]
- Explanation:
The three copies of 7 are all closer to 100 than the value 1 is.
Constraints
- 1 ≤ k ≤ n ≤ 105, where n is the length of
nums - k ≤ 500 in this problem set so that answers stay small
- -109 ≤ nums[i], x ≤ 109
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms
Expected complexity
- Time
- O(n + k log k)
- Space
- O(n)