class Solution {
public int[] searchRange(int[] nums, int target) {
int result = getFirstIndex(nums, target);
if(nums.length == result || nums[result] != target){
return new int[]{-1, -1};
}
return new int[]{result, getFirstIndex(nums, target + 1) - 1};
}
public int getFirstIndex(int[] nums, int target){
int left = 0;
int right = nums.length - 1;
int mid;
while(left <= right){
mid = left + ((right - left) >> 1);
if(nums[mid] >= target){
right = mid - 1;
}else{
left = mid + 1;
}
}
return left;
}
}
在排序数组中查找元素的第一个和最后一个位置
最新推荐文章于 2024-08-29 16:57:08 发布