剑指 Offer 53 - I. 在排序数组中查找数字 I
统计一个数字在排序数组中出现的次数。
示例 1:
输入: nums = [5,7,7,8,8,10], target = 8
输出: 2
示例 2:
输入: nums = [5,7,7,8,8,10], target = 6
输出: 0
题解
经典的二分查找的问题,左边是那个值最开始出现的地方
class Solution {
public int search(int[] nums, int target) {
//二分啊
int left =0,right = nums.length-1;
int count = 0;
while(left<right){
int mid = (left+right)/2;
if(nums[mid]>=target)
right=mid;
if(nums[mid]<target)
left = mid+1;
}
while(left<nums.length&&nums[left++]==target)
count++;
return count;
}
}