题链接:https://leetcode-cn.com/problems/zai-pai-xu-shu-zu-zhong-cha-zhao-shu-zi-lcof/
题描述:
解题思路:
使用两次二分查找左右边界,数字出现次数即为 right - left - 1。
代码实现:
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var search = function(nums, target) {
let i = 0;
let j = nums.length - 1;
while (i <= j) {
let mid = Math.floor(i + (j - i) / 2);
if (nums[mid] <= target) {
i = mid + 1;
} else {
j = mid - 1;
}
}
let right = i;
i = 0;
j = nums.length - 1;
while (i <= j) {
let mid = Math.floor(i + (j - i) / 2);
if (nums[mid] >= target) {
j = mid - 1;
} else {
i = mid + 1;
}
}
let left = j;
return right - left - 1;
};
时间复杂度:O(log n)
空间复杂度:O(1)