二分查找是在面试中经常会遇到的面试题,根据普通的二分查找还衍生出了二分查找的其他情况,比如有序数组中的目标出现多次,利用二分查找返回在最左边出现的目标值或者是最右边出现的目标值。
查找最左边出现的目标值
public static int binarySearchLeft(int[] arr,int target){
if(arr==null||arr.length==0){
return -1;
}
int left = 0;
int right = arr.length-1;
while(left<right){
int mid = (left+right)/2;
if(arr[mid]<target){
left = mid+1;
}else {
right = mid;
}
}
if(arr[right]==target){
return right;
}
return -1;
}
查找最右边出现的目标值
public static int binarySearchRight(int[] arr,int target){
if(arr==null||arr.length==0){
return -1;
}
int left = 0;
int right = arr.length-1;
while(left<right){
int mid = (left+right)/2;
if(arr[mid]<=target){
left = mid;
}else {
right = mid-1;
}
}
if(arr[left]==target){
return left;
}
return -1;
}
END