704. Binary Search
class Solution {
public int search(int[] nums, int target) {
// search range: [0, nums.length - 1]
int left = 0;
int right = nums.length - 1;
// when left > right end this loop
while (left <= right) {
// avoid integer overflow
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
return mid;
} else if (nums[mid] < target) {
left = mid + 1;
} else if (nums[mid] > target) {
right = mid - 1;
}
}
return -1;
}
}