题目描述
统计一个数字在排序数组中出现的次数。
示例
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/c05653f40bebacd8c8178ea893710f71.png)
思路
1、暴力法
- 注意while循环中先判断数组是否越界再判断其值是否相等
class Solution {
public int search(int[] nums, int target) {
int count = 0;
for(int i = 0; i < nums.length; i++) {
if(nums[i] == target) {
while(i < nums.length && nums[i] == target) {
i++;
count++;
}
return count;
}
}
return count;
}
}
二分法
class Solution {
public int search(int[] nums, int target) {
int left = 0, right = nums.length - 1;
while(left <= right) {
int mid = (left + right) / 2;
if(nums[mid] <= target) left = mid + 1;
else right = mid - 1;
}
int R = left;
left = 0;
while(left <= right) {
int mid = (left + right) / 2;
if(nums[mid] < target) left = mid + 1;
else right = mid - 1;
}
int L = right;
return R - L - 1;
}
}