很普通的二分查找吧
public class Solution {
public int[] searchRange(int[] nums, int target) {
int start = 0;
int middle = 0;
int end = 0;
int []xy = new int[2];//xy[0]是范围的第一个值,xy[1]是范围的第二个值
if(nums.length==0){
xy[0]=-1;
xy[1]=-1;
return xy;
}
int i=0,j=nums.length-1;
while(i<j){//二分查找,内部不判断是否命中
middle = i+(j-i)/2;
if(nums[middle]>target){
j = middle - 1;
}else if(nums[middle]==target){
j = middle;
break;
}else{
i = middle+1;
}
}//默认情况如果有值,命中的值的下标都是j
start = j;
end = j;
if(j<0||j>nums.length-1||nums[j]!=target){//这个是判断是否有这个值
xy[0]=-1;
xy[1]=-1;
return xy;
}
for(i=j-1;i>=0;i--){
if(nums[i] == nums[j])
start=i;
else
break;
}
for(i=j+1;i<nums.length;i++){
if(nums[i] == nums[j])
end=i;
else
break;
}
xy[0]=start;
xy[1]=end;
return xy;
}
}