Binary Search — Binary Search
Given an ascending list of unique numbers, report the index where a requested number sits, or a negative marker if it is absent.
Binary Search · Easy
The problem
A catalog is sorted by item code, strictly increasing, and you must find a given code. You get the list of integers nums and a target value. Report the position of the target in the list, or -1 if the list does not contain it.
The story
A parts warehouse keeps its catalogue sorted by item code, strictly increasing with no repeats: usually a handful of codes, but some catalogues hold thousands, each between -4000 and 4000. A picker asks for a target code between -4500 and 4500. Report the position of that code in the catalogue, or -1 if the warehouse doesn't stock it.
What to return
- Return the 0-based index i with nums[i] == target.
- Return -1 when the target is not in the list.
Constraints
- 1 <= nums.length <= 2000
- -4000 <= nums[i] <= 4000
- nums is strictly increasing (no duplicates)
- -4500 <= target <= 4500
- Your code may run at most 232 counted steps on the largest case.
Example
- Input
nums = [-8, -3, 1, 6, 14, 20], target = 14- Output
4