解题:利用二分找到一个相等的元素,之后再左右边界
class Solution {
public int[] searchRange(int[] nums, int target) {
int n=nums.length;
int l=0,r=n-1;
int start=-1,end=-1;
while(l<=r){
int mid=(r+l)/2;
if(nums[mid]==target){
start=mid;
end=mid;
int temp=mid;
while(nums[mid]==target){
mid--;
if(mid==-1) break;
}
start=mid+1;
while(nums[temp]==target){
temp++;
if(temp==n) break;
}
end=temp-1;
break;
}else if(nums[mid]>target){
r=mid-1;
}else{
l=mid+1;
}
}
return new int[]{start,end};
}
}
在找到一个一个等于target数时做两种不同的选择,r=mid-1,l=mid+1可以找出左右边界
class Solution {
public int[] searchRange(int[] nums, int target) {
return new int[]{binarySearchLeftBound(nums, target),binarySearchRightBound(nums, target)};
}
public int binarySearchLeftBound(int[] nums, int target) {
int l = 0, r = nums.length - 1;
while (l <= r) {
int mid = l + ((r - l) >> 1);
if (nums[mid] < target) {
l = mid + 1;
} else if (nums[mid] > target) {
r = mid - 1;
} else if (nums[mid] == target) {
r = mid - 1;
}
}
if (l >= nums.length || nums[l] != target) return -1;
return l;
}
public int binarySearchRightBound(int[] nums, int target) {
int l = 0, r = nums.length - 1;
while (l <= r) {
int mid = l + ((r - l) >> 1);
if (nums[mid] < target) {
l = mid + 1;
} else if (nums[mid] > target) {
r = mid - 1;
} else if (nums[mid] == target) {
l = mid + 1;
}
}
if (r < 0 || nums[r] != target) return -1;
return r;
}
}