class Solution {
public int[] searchRange(int[] nums, int target) {
int[] res=new int[2];
res[0]=findleft(nums,target);
res[1]=findright(nums,target);
return res;
}
public int[] searchRange(int[] nums, int target) {
int[] res=new int[2];
res[0]=findleft(nums,target);
res[1]=findright(nums,target);
return res;
}
private int findright(int[] nums, int target) {
int left=0;
int right=nums.length; //向左或向右紧缩时,就用nums.length; 因此while里为<号 不带等号 等就越界
while (left<right) {
int mid=(left+right)>>1;
if (nums[mid]==target) {
left=mid+1; //向右,因为是right=nums.length;所以是左闭右开
}
else if (nums[mid]<target) {
left=mid+1;
}
else {
right=mid;
}
}
if (left == 0) return -1; //向右紧缩 却缩到了最左侧 说明没找到
return nums[left-1] == target ? (left-1) : -1;
}
int left=0;
int right=nums.length; //向左或向右紧缩时,就用nums.length; 因此while里为<号 不带等号 等就越界
while (left<right) {
int mid=(left+right)>>1;
if (nums[mid]==target) {
left=mid+1; //向右,因为是right=nums.length;所以是左闭右开
}
else if (nums[mid]<target) {
left=mid+1;
}
else {
right=mid;
}
}
if (left == 0) return -1; //向右紧缩 却缩到了最左侧 说明没找到
return nums[left-1] == target ? (left-1) : -1;
}
private int findleft(int[] nums, int target) {
int left=0;
int right=nums.length;
while (left<right) {
int mid=(left+right)>>1;
if (nums[mid]==target) {
right=mid; //向左紧缩,因为是right=nums.length;所以是左闭右开
}
else if (nums[mid]<target) {
left=mid+1;
}
else {
right=mid;
}
}
if (left >= nums.length || nums[left] != target)//向左紧缩,却缩到了最右侧 说明没找到
return -1;
return left;
}
}
}