就是分成两个函数来分别求数组中的数的位置,有注意的就是就算等于目标数也不结束,所以要写if,else if 和else,别分开。
class Solution {
public int[] searchRange(int[] nums, int target) {
if(nums==null || nums.length==0)return new int[]{-1,-1};
int start=binarySerchStart(nums,target,0,nums.length-1);
if(start==-1)return new int[]{-1,-1};
int end=binarySerchEnd(nums,target,0,nums.length-1);
return new int[]{start,end};
}
public int binarySerchStart(int[] nums, int target,int lo,int hi){
while(lo<=hi){
int mid=lo+((hi-lo)>>1);
if(nums[mid]==target){
if(mid==0 || (mid-1>=0 && nums[mid-1]!=nums[mid])){
return mid;
}else{
hi=mid-1;
}
}else if(nums[mid]>target){
hi=mid-1;
}else{
lo=mid+1;
}
}
return -1;
}
public int binarySerchEnd(int[] nums, int target,int lo,int hi){
while(lo<=hi){
int mid=lo+((hi-lo)>>1);
if(nums[mid]==target){
if(mid==nums.length-1 || (mid+1<=nums.length-1 && nums[mid]!=nums[mid+1])){
return mid;
}else{
lo=mid+1;
}
}else if(nums[mid]>target){
hi=mid-1;
}else{
lo=mid+1;
}
}
return -1;
}
}