剑指 Offer 53 - I. 在排序数组中查找数字 I

题目

统计一个数字在排序数组中出现的次数。

示例 1:

1
2
输入: nums = [5,7,7,8,8,10], target = 8
输出: 2

示例2:

1
2
输入: nums = [5,7,7,8,8,10], target = 6
输出: 0

提示:

  • 0 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • nums 是一个非递减数组
  • -10^9 <= target <= 10^9

解法

解法一:

JAVA

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public int search(int[] nums, int target) {
int begin = 0;
int end = nums.length - 1;
int count = 0;
while (begin < end) {
int mid = (begin + end) / 2;
if(nums[mid]>=target) {
end = mid;
}
if(nums[mid]<target) {
begin = mid + 1;
}
}
while (begin < nums.length && nums[begin++] == target) {
count++;
}
return count;
}
0%