//找到开始位置下标
int leftRange(int *nums,int numsSize,int target)
{
int left = 0;
int right = numsSize - 1;
int range;
while(left <= right)
{
int mid = (right - left) / 2 + left; //防止加法发生整形溢出
if(nums[mid] >= target) //只要mid的左边有target元素,就向左检索
{
right = mid - 1;
range = right; //存储可能成为开始位置的下标
}
else
left = mid + 1;
}
return range+1; //最后一次right=mid-1使得left>right,可以认为这是一个无效运算,因此需要将-1抵消
}
//找到结束位置下标
int rightRange(int *nums,int numsSize,int target)
{
int left = 0;
int right = numsSize - 1;
int range;
while(left <= right)
{
int mid = (right - left) / 2 + left;
if(nums[mid] > target)
right = mid - 1;
else //只要mid的右边有target元素,就向右检索
{
left = mid + 1;
range = left;
}
}
return range-1; //最后一次left=mid+1使得left>right,可以认为这是一个无效运算,因此需要将1抵消
}
int* searchRange(int* nums, int numsSize, int target, int* returnSize){
*returnSize = 2;
int *number = (int *)malloc(sizeof(int) * (*returnSize));
int left = 0;
int right = numsSize - 1;
int flag = 0;
while(left <= right) //首先判断target是否存在于数组中
{
int mid = (right - left) / 2 + left;
if(nums[mid] < target)
left = mid + 1;
else if(nums[mid] > target)
right = mid - 1;
else
{
flag = 1;
break;
}
}
if(flag) //如果存在
{
number[0] = leftRange(nums,numsSize,target);
number[1] = rightRange(nums,numsSize,target);
}
else //如果不存在
number[0] = number[1] = -1;
return number;
}