FunctionRacerProblemsRace

K Closest Values

MediumSorting and searchingPython, JavaScript, TypeScript, Java, C++

nums is sorted in non-decreasing order. Return the k items of nums that are closest to target, as a list in non-decreasing order. The distance of an item x is abs(x - target).

An item a is preferred over an item b when a is closer to target, or when they are equally close and a < b; the answer holds the k most preferred items. Items with the same value count separately, so the answer can hold repeats. The chosen items always form a block of neighbours in nums.

Example 1

nums [1,3,6,8,10]
k 3
target 7
returns [6,8,10]

6 and 8 are 1 away from 7, and 10 is 3 away, closer than 3, which is 4 away.

Example 2

nums [1,4,6,9]
k 3
target 5
returns [1,4,6]

4 and 6 are closest; for the third spot 1 and 9 are both 4 away, and the smaller one, 1, wins.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Sorting and searching problems