Binary Search
Part of Practice: Search Templates
You are given an array of integers nums that is sorted in ascending order, and a number target. Return the index where target appears in the array, or -1 if it is not there.
Your solution must run in O(log n) time, which rules out scanning the array from left to right.
Constraints that matter: all values in nums are unique, and the array can hold up to about 10,000 elements.
Examples
- Input:
- nums = [-1, 0, 3, 5, 9, 12], target = 9
- Output:
- 4
9 is at index 4 of the array.
- Input:
- nums = [-1, 0, 3, 5, 9, 12], target = 2
- Output:
- -1
2 is not in the array, so we return -1.
Hints
One at a time — struggle first, peek second.
Your thinking space — verify on LeetCode, then mark it.