Binary Search Target Index
This is the standard binary search problem: given a sorted array and a target value, return the index where the target appears.
If the target is not in the array, return -1. Because the array is sorted, you do not need to scan from left to right. You can compare with the middle value and throw away half of the search space each time.
For example, if nums = [-1,0,3,5,9,12] and target = 9, the answer is 4. If target = 2, the answer is -1 because 2 does not appear anywhere in the array.
So the task is to search the sorted array efficiently and return the target's index, or -1 if it does not exist.
Example Input & Output
The target value 2 is not present in the array, so return -1.
The array is empty, so return -1.
The target value 9 is found at index 4 in the array.
Algorithm Flow

Solution Approach
The idea behind binary search is simple: compare the target with the middle value, then keep only the half where the target could still exist.
If nums[mid] === target, we are done. If nums[mid] < target, the target must be on the right. If nums[mid] > target, the target must be on the left.
If the loop finishes without finding the target, then it is not in the array, so return -1.
This runs in O(log n) time and uses O(1) extra space.
Best Answers
class Solution {
public int search(Object nums, Object target) {
int[] arr = (int[]) nums;
int t = (int) target;
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == t) {
return mid;
} else if (arr[mid] < t) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
