Find target
public int binarySearch(int[] nums, int target) {
int left = 0, right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (target > nums[mid]) left = mid + 1;
else if (target < nums[mid]) right = mid - 1;
else if (target == nums[mid]) return mid;
}
return -1;
}Find first occurrence of the target
public int binarySearch(int[] nums, int target) {
int left = 0, right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (target > nums[mid]) left = mid + 1;
else if (target < nums[mid]) right = mid - 1;
else if (target == nums[mid]) right = mid - 1;
}
if (left >= nums.length || nums[left] != target) return -1;
return left;
}Find last occurrence of the target
public int binarySearch(int[] nums, int target) {
int left = 0, right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (target > nums[mid]) left = mid + 1;
else if (target < nums[mid]) right = mid - 1;
else if (target == nums[mid]) left = mid + 1;
}
if (right < 0 || nums[right] != target) return -1;
return right;
}