问题描述
思路
找出第一个大于等于target的下标值,判断该下标对应值是否为target并且下标是否符合数字下标范围, 如果满足则为左端点,找出第一个大于等于target+1的下标值的前一个下标值为右端点
java实现
public class Solution {
public int[] searchRange(int[] nums, int target) {
int []results=new int[]{-1,-1};
int start = firstGreaterEqual(nums, target);
if (start == nums.length || nums[start] != target) {
return results;
}
int end = firstGreaterEqual(nums, target + 1) - 1;
results[0]=start;
results[1]=end;
return results;
}
//找出第一个大于等于目标的数
public int firstGreaterEqual(int[] nums, int target){
int left=0;
int right=nums.length;
while(left<right){
int middle=left+(right-left)/2;
if(target>nums[middle])
left=middle+1;
else
right=middle;
}
return left;
}
}
来源:https://blog.csdn.net/weixin_44135282/article/details/99546923