Binary Search Application
Basic Application:
Finding target (peak, boundary, median)
- Sorted Array(Prefix Sum array)
- Rotated sorted array(have Peak or nadir)
- Two sorted Array
- BST
Advanced Application:
- Math Calculation(power, sqrt)
- Core of Binary Search:
- The result set is in a certain interval
- If current test results are not satisfied, we can shrink our result set by removing part of the results which never be the result.
Binary Search classic problems:
Basic Manipulation
Regualr Version:
int left = 0, right = nums.length - 1;
while (left < right) {
int mid = left + ((right - left) >> 1);
if (nums[mid == target]) {
return true;
} else if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid;
}
}
Find First or Last Position:
int left = 0, right = nums.length - 1;
while (left < right) {
int mid = left + ((right - left) >> 1);
if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid;
}
}
First position: left
Last position: left == 0 ? 0 : --left
Insert position : nums[left] < target ? left + 1 : left