Skip to content
BytePatterns

Closest K Values to a Target

EasyHeaps#top-k#max-heap~15m

Problem

Given an unsorted list of integers nums, a target and a count k, return the k values closest to the target. When two values are equally far away, the smaller value is closer. Return the chosen values in ascending order.

Examples

Input:  nums = [9, 2, 14, 5, 7, 11], target = 8, k = 3
Output: [5, 7, 9]
Why:    7 and 9 are 1 away, then 5 and 11 tie at 3 and the smaller value wins
Input:  nums = [1, 10, 4, 4], target = 4, k = 2
Output: [4, 4]
Why:    repeated values count separately
Input:  nums = [3], target = 100, k = 1
Output: [3]
Why:    edge case, the only value is the closest one however far it is

Hints

0 / 3

Stuck on the idea rather than the code? K Closest Points covers it.