🔗:代码随想录:二分查找的算法讲解:有关left<=right和left<right的区别
class Solution {
public int[] searchRange(int[] nums, int target) {
int n=nums.length;
int l=0,h=n-1;
if(nums==null){
return null;
}
if(n==0){
return new int[]{-1,-1};
}
if(target<nums[0]||target>nums[n-1]){
return new int[]{-1,-1};
}
int m=(l+h)/2;
boolean Find=false;
while(l<=h){
m=(l+h)/2;
if(nums[m]<target){
l=m+1;
}
else if(nums[m]>target){
h=m-1;
}else{
Find=true;
break;
}
}
if(nums[m]==target&&Find){
int i=m,j=m;
while(i>0&&nums[i]==target&&nums[i-1]==nums[i]){
i--;
}
while(j+1<n&&nums[j]==target&&nums[j+1]==nums[j]){
j++;
}
return new int[]{i,j};
}
return new int[]{-1,-1};
}
}