Nearest Value in a Sorted List
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
1 <= len(nums) <= 100-1000 <= nums[i], target <= 1000numsis sorted in non-decreasing order
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.