704. Binary Search
- Goal: Search for a
target
in a sorted arraynums
. Return its index, or-1
if not found. - Constraint: Must achieve \(O(log n)\) time complexity.
Example
1 | Input: nums = [-1, 0, 3, 5, 9, 12], target = 9 |
Quick Steps for Binary Search
Initial Setup
- Set
left = 0
,right = nums.length - 1
.
Middle Calculation
- Compute
mid = Math.floor((left + right) / 2)
.
Comparison
- If
nums[mid] == target
: Returnmid
. - If
nums[mid] < target
: Moveleft
tomid + 1
. - If
nums[mid] > target
: Moveright
tomid - 1
.
Repeat
- Continue until
left > right
.
Return
- If found, return the index; else, return
-1
.
JavaScript Implementation
1 | /** |
Summary
- Binary Search: Divide and conquer by halving the search space.
- Key Points: Efficiently narrows down the search to find the target in \(O(log n)\) time.