Given a sorted array of distinct integers, return the index of a target value, or -1 if absent.
It's the exact template every other binary-search problem in this course builds on.
A sorted array with a single target to locate is the textbook binary-search case — establish the loop invariant here before touching harder variants.
Maintain an inclusive range `[lo, hi]`. While `lo <= hi`, compute `mid = lo + (hi - lo) / 2` to avoid overflow. If `nums[mid] == target`, return `mid`. If `nums[mid] < target`, the target must be to the right, so `lo = mid + 1`; otherwise `hi = mid - 1`. If the loop ends without a match, the target isn't present.
class Solution {
public int search(int[] nums, int target) {
int lo = 0, hi = nums.length - 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] == target) {
return mid;
} else if (nums[mid] < target) {
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return -1;
}
}