题目
统计一个数字在排序数组中出现的次数。
示例 1:
输入: nums = [5,7,7,8,8,10], target = 8
输出: 2
示例 2:
输入: nums = [5,7,7,8,8,10], target = 6
输出: 0
提示:
0 <= nums.length <= 10
5-10
9<= nums[i] <= 10
9nums
是一个非递减数组-10
9<= target <= 10
9
注意: 本题与主站 34 题相同(仅返回值不同):https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/
题解
java
public int search(int[] nums, int target) {
// 二分查找
BiFunction<Integer, Integer, Integer> binarySearch = new BiFunction<Integer, Integer, Integer>() {
@Override
public Integer apply(Integer start, Integer end) {
if (start > end || nums[end] < target || nums[start] > target) {
return 0;
}
if (nums[end] == target || nums[start] == target) {
int count = 0;
for (int i = start; i <= end; i++) {
count += nums[i] == target ? 1 : 0;
}
return count;
}
int mid = (start + end) >> 1;
return this.apply(start, mid) + this.apply(mid + 1, end);
}
};
return binarySearch.apply(0, nums.length - 1);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25