mirror of
https://github.com/prdlk/leetcode.git
synced 2026-09-17 07:26:27 +00:00
64 lines
1.3 KiB
Markdown
64 lines
1.3 KiB
Markdown
## Binary Search
|
|||
|
|
|
||
|
|
Halve a **monotonic** search space each step → O(log n).
|
||
|
|
|
||
|
|
---
|
||
|
|
|
||
|
|
## Recognition
|
||
|
|
|
||
|
|
- Sorted input + "find / insert position"
|
||
|
|
- "Minimize the maximum" / "first value where condition flips"
|
||
|
|
- Answer itself is numeric and checkable → binary search **on the answer**
|
||
|
|
|
||
|
|
---
|
||
|
|
|
||
|
|
## Template
|
||
|
|
|
||
|
|
```js
|
||
|
|
function search(nums, target) {
|
||
|
|
let lo = 0;
|
||
|
|
let hi = nums.length - 1;
|
||
|
|
while (lo <= hi) {
|
||
|
|
const mid = lo + ((hi - lo) >> 1);
|
||
|
|
if (nums[mid] === target) return mid;
|
||
|
|
if (nums[mid] < target) lo = mid + 1;
|
||
|
|
else hi = mid - 1;
|
||
|
|
}
|
||
|
|
return -1; // lo is the insert position
|
||
|
|
}
|
||
|
|
```
|
||
|
|
|
||
|
|
---
|
||
|
|
|
||
|
|
## First-true boundary
|
||
|
|
|
||
|
|
```js
|
||
|
|
// smallest index where ok(i) is true; ok is false...false true...true
|
||
|
|
let lo = 0;
|
||
|
|
let hi = n; // exclusive; n means "never true"
|
||
|
|
while (lo < hi) {
|
||
|
|
const mid = lo + ((hi - lo) >> 1);
|
||
|
|
if (ok(mid)) hi = mid;
|
||
|
|
else lo = mid + 1;
|
||
|
|
}
|
||
|
|
return lo;
|
||
|
|
```
|
||
|
|
|
||
|
|
Most "hard" binary searches are this shape in disguise.
|
||
|
|
|
||
|
|
---
|
||
|
|
|
||
|
|
## Pitfalls
|
||
|
|
|
||
|
|
- Off-by-one: pick `lo <= hi` **or** `lo < hi` and stay consistent
|
||
|
|
- `mid = lo + ((hi - lo) >> 1)` avoids overflow and floats
|
||
|
|
- No progress → infinite loop: every branch must shrink the range
|
||
|
|
|
||
|
|
---
|
||
|
|
|
||
|
|
## Recall
|
||
|
|
|
||
|
|
- What property must the search space have? (not "sorted" — *monotonic*)
|
||
|
|
- Where does `lo` land when the target is absent?
|
||
|
|
- When do you search the answer space instead of the array?
|