统计一个数字在排序数组中出现的次数。
示例 1:
输入: nums = [5,7,7,8,8,10], target = 8
输出: 2
示例 2:
输入: nums = [5,7,7,8,8,10], target = 6
输出: 0
限制:
0 <= 数组长度 <= 50000
解题思路
- 先用二分法查找出其中一个目标元素
- 再向目标元素两边查找目标元素
代码
class Solution {public int search(int[] nums, int target) {int l = 0, r = nums.length - 1;while (l <= r) {int mid = (r - l) / 2 + l;if (nums[mid] == target) {int left = mid-1, right = mid+1;while (left >= 0 && nums[left] == target)left--;while (right < nums.length && nums[right] == target)right++;return right - left - 1;} else if (nums[mid] > target)r = mid - 1;else l = mid + 1;}return 0;}
}