Binary search · Easy
A settings control allows only a sorted list of numeric values. When a requested value is unavailable, the control snaps to the nearest allowed value. The tie rule must be predictable so repeated requests do not produce different choices.
Return the allowed value closest to the target and choose the smaller value on an equal-distance tie.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
{ nums: integer[], target: integer }
Fields
- nums is already sorted in nondecreasing numeric order. Do not sort it again.
- target is an integer between -2000000000 and 2000000000.
Output
Return value
- Return the selected value, not its index or distance. Empty input returns null.
- An exact match wins. With equal distances, select the numerically smaller value.
Constraints
- 0 <= nums.length <= 100000; -1000000000 <= nums[i] <= 1000000000.
- All totals and counts fit exactly in a safe JSON integer.
Examples
Example 1
{
"nums": [
2,
6,
9
],
"target": 4
}Returns
2Example 2
{
"nums": [
2,
6,
9
],
"target": 20
}Returns
9Required complexity
O(log(n + 1)) search time and O(1) auxiliary space