← All problemsExample 1 Example 2 Example 3
Problem
Binary Search
Easy- binary-search
nums is sorted in ascending order and has no repeated values. Return the index of target in it, or -1 if target is not there.
A scan from the left is too slow. The search has to take O(log n) time.
- Input
nums = [3, 8, 14, 21, 30, 47, 52], target = 30- Output
4- Explanation
30 is stored at index 4.
- Input
nums = [3, 8, 14, 21, 30, 47, 52], target = 25- Output
-1- Explanation
25 would sit between 21 and 30, but it is not in the array.
- Input
nums = [], target = 4- Output
-1- Explanation
an empty array holds nothing to find.
Constraints:
0 <= nums.length <= 10^5-10^9 <= nums[i], target <= 10^9numsis sorted in ascending order and its values are distinct
Tab indents. Press Esc, then Tab to leave the editor.
Ctrl or ⌘ + Enter runs the tests.
Run your code to see every test here. Nothing is submitted or recorded.