34.在排序数组中查找元素的第一个和最后一个元素
class Solution {
public int[] searchRange(int[] nums, int target) {
int find=reverse(nums,target);
if(find==-1){
return new int[]{-1,-1};
}
int left=find-1;
int rigth=find+1;
while(left>=0&&nums[left]==target){
left--;
}
left++;
while(rigth<=nums.length-1&&nums[rigth]==target){
rigth++;
}
rigth--;
return new int[]{left,rigth};
}
public int reverse(int[] nums, int target){
int left=0;
int rigth=nums.length-1;
while(left<=rigth){
int mid=(left+rigth)/2;
if(nums[mid]>target){
rigth=mid-1;
}else if(nums[mid]<target){
left=left+1;
}else{
return mid;
}
}
return -1;
}
}