1. Binary Search
Template
Basic template
// This template is to find the target from a sorted array, not consider duplicates
int binarySearch(int[] nums, int target) {
int left = 0, right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left)/2;
if (nums[mid] == target) {
return mid;
} else if (nums[mid] > target) {
right = mid - 1;
} else if (nums[mid] < target) {
left = mid + 1;
}
}
return -1;
}
// The termination condition is nums[mid] == target or left > rightLeft bound
Right bound
总结:如果只是找到target,用left <= right, 但找左边界(最近的少于target的值),或者右边界,用left < right 更加灵活
Typical problems
Find peak element from the array, left < right is useful for comparing index and index + 1, which is used for find local max/min
Search in a rotated sorted array, notice either the left half is ordered or right half is ordered, and the target either in this side or in the other side
Eat balance - capacity find problems
Last updated