FunctionRacerProblemsRace

Nearest Value in a Sorted List

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

nums is sorted in non-decreasing order and has at least one item. Return the value in nums that is closest to target, meaning the one with the smallest abs(value - target). If two different values are equally close, one below target and one above, return the smaller of the two.

If target itself is in the list, the answer is target.

Example 1

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

4 and 6 are both 1 away from 5; the smaller one, 4, wins.

Example 2

nums [1,4,6,9]
target 8
returns 9

9 is 1 away from 8, closer than 6, which is 2 away.

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