方法一:拆分成两个函数,一个找左边界,一个找右边界,default值设为-1
int s_left(int *nums,int numsSize,int target){
int left=0,right=numsSize-1,middle,leftboard=-1;
while(left<=right){
middle=(left+right)/2;
if(target<nums[middle])
right=middle-1;
else if(target>nums[middle])
left=middle+1;
else{
leftboard=middle;
right=middle-1;
}
}
return leftboard;
}
int s_right(int *nums,int numsSize,int target){
int left=0,right=numsSize-1,middle,rightboard=-1;
while(left<=right){
middle=(left+right)/2;
if(target<nums[middle])
right=middle-1;
else if(target>nums[middle])
left=middle+1;
else{
rightboard=middle;
left=middle+1;
}
}
return rightboard;
}
方法二:合并成一个函数,传递一个选择mode的值
true:左边界
当mid的值==target时,记录ans=mid,继续向左找
false:有边界
当mid值==target时,向右找,当mid的值大于target时,更新这个大于它的临界值,
若一直找不到大值,则右边界有default值numsSize
注意:target值找不到有三种情况,一种小于所有值,一种大于所有值,一种位于中间
此时都有left边界>right边界
官方题解:
int binarySearch(int* nums, int numsSize, int target, bool lower) {
int left = 0, right = numsSize - 1, ans = numsSize;
while (left <= right) {
int mid = (left + right) / 2;
if (nums[mid] > target || (lower && nums[mid] >= target)) {
right = mid - 1;
ans = mid;
} else {
left = mid + 1;
}
}
return ans;
}
int* searchRange(int* nums, int numsSize, int target, int* returnSize) {
int leftIdx = binarySearch(nums, numsSize, target, true);
int rightIdx = binarySearch(nums, numsSize, target, false) - 1;
int* ret = malloc(sizeof(int) * 2);
*returnSize = 2;
if (leftIdx <= rightIdx && nums[leftIdx] == target && nums[rightIdx] == target) {
ret[0] = leftIdx, ret[1] = rightIdx;
return ret;
}
ret[0] = -1, ret[1] = -1;
return ret;
}