统计一个数字在排序数组中出现的次数。
示例 1:
输入: nums = [5,7,7,8,8,10], target = 8
输出: 2
示例 2:
输入: nums = [5,7,7,8,8,10], target = 6
输出: 0
限制:
0 <= 数组长度 <= 50000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/zai-pai-xu-shu-zu-zhong-cha-zhao-shu-zi-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:这种题肯定不用暴力,因为他是有序的所以应该用二分。
我的思路是找到target的位置(没有的话就返回0),然后前后进行遍历就行了。
class Solution {
public int search(int[] nums, int target) {
if(nums.length<=0){
return 0;
}
int l = 0;
int r = nums.length-1;
int count = 0;
while(l<r){
int mid = (l+r)/2;
if(nums[mid]==target){
l = mid;
break;
}else if(nums[mid]>target){
r = mid-1;
}else{
l = mid+1;
}
}
if(nums[l]==target){
count++;
}else{
return 0;
}
for(int i=l+1;i<nums.length;i++){
if(nums[i]==target){count++;}
else{break;}
}
for(int i=l-1;i>=0;i--){
if(nums[i]==target){count++;}
else{break;}
}
return count;
}
}