先用二分找到目标数字,同时也缩小了区间
再用遍历找到目标区间的边界
/** 典型二分,说了有序数组*/
public int search(int[] nums, int target) {
/** 先确立好边界*/
int left = 0;
int right = nums.length - 1;
/** 开始二分,当left > right 时结束*/
while (left <= right){
int mid = left + (right - left) / 2;
if (nums[mid] < target) left = mid + 1;
else if(nums[mid] > target) right = mid - 1;
else {//当找到目标数字
if (nums[left] != target) left++;//如果左边界不为目标值,向右移
else if (nums[right] != target) right--;
else break;
}
}
return right - left + 1;
}