First Position of Target
If the array is [1, 2, 3, 3, 4, 5, 10], for given target 3, return 2.
class Solution {
/**
* @param nums: The integer array.
* @param target: Target to find.
* @return: The first position of target. Position starts from 0.
*/
public int binarySearch(int[] nums, int target) {
//write your code here
if(nums.length == 0) return -1;
int start = 0;
int end = nums.length - 1;
while (start < end){
int midIndex = start + (end - start) / 2;
int mid = nums[midIndex];
if (target <= mid) {
end = midIndex;
} else {
start = midIndex + 1;
}
}
return nums[start] == target ? start : -1;
}
}
Because we want to find the first index of the target, we target is equal to the mid, we set end = midIndex (not end = midIndex - 1) to include the possible index into the range. since the while condition is start < end and start is always increasing, there will be no dead loop.
Another example to compare is :
Last Position of Target
public class Solution {
/**
* @param nums: An integer array sorted in ascending order
* @param target: An integer
* @return an integer
*/
public int lastPosition(int[] nums, int target) {
// Write your code here
if(nums.length == 0) return -1;
int start = 0;
int end = nums.length - 1;
while (start < end){
int midIndex = start + (end - start)/2 + (end - start)%2;
int mid = nums[midIndex];
if(mid <= target){
start = midIndex;
}
else if(mid > target){
end = midIndex - 1;
}
}
return nums[start] == target ? start : -1;
}
}
using the same idea, when mid == target, start = midIndex (not midIndex + 1) to include the possible answer in the range. However, if start do not move, it is possible that when the gap is 1 (end = start + 1) we will have dead loop. in order to solve that, when computing the mid, we should take the ceilings instead of the floors. Then we ensure mid will always bigger than start and we will not get into dead loop.