题目
统计一个数字在排序数组中出现的次数。
示例 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^9
nums
是一个非递减数组-10^9 <= target <= 10^9
**注意:**本题与主站 34 题相同(仅返回值不同):https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/
解题
方法一:二分查找
思路
二分查找裸题,与【二分查找】在排序数组中查找元素的第一个和最后一个位置差不多,都是查找目标元素的左右边界,只不过本题要把左右边界索引相减加一求出目标元素出现的次数。
二分查找 - 相等 - 左边界 二分查找 - 相等 - 右边界
代码
class Solution {
int leftBound(int[] nums, int target) {
int left = 0, right = nums.length;
while (left < right) {
int mid = left + ((right - left) >> 1);
if (nums[mid] >= target) right = mid;
else left = mid + 1;
}
return left < nums.length && nums[left] == target ? left : -1;
}
int rightBound(int[] nums, int target) {
int left = 0, right = nums.length;
while (left < right) {
int mid = left + ((right - left) >> 1);
if (nums[mid] > target) right = mid;
else left = mid + 1;
}
return --left >= 0 && nums[left] == target ? left : -1;
}
public int search(int[] nums, int target) {
int lb = leftBound(nums, target);
if (lb == -1) return 0;
return rightBound(nums, target) - lb + 1;
}
}
评论区