Binary search · Easy
A lookup service stores sorted numeric keys and may have several records under the same key. A detail view must begin at the earliest matching record. Returning an arbitrary equal midpoint would omit earlier matching records.
Find the first exact occurrence of the target in the sorted keys or report that it is absent.
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 smallest zero-based index where nums[index] equals target. Return -1 when absent.
- An insertion position is not a match unless the value at that position equals target.
Constraints
- 0 <= nums.length <= 100000; -1000000000 <= nums[i] <= 1000000000.
- All totals and counts fit exactly in a safe JSON integer.
Examples
Example 1
{
"nums": [
1,
2,
2,
4
],
"target": 2
}Returns
1Example 2
{
"nums": [
1,
4
],
"target": 3
}Returns
-1Required complexity
O(log(n + 1)) search time and O(1) auxiliary space