Below code is generic can be used to find occurrences of any number provided array is sorted with only 2 unique element
var getOneCount = function (nums, target) {
let high = nums.length - 1;
let low = 0;
while (low <= high) {
let mid = parseInt((low + high) / 2);
if (nums[mid] > target) {
high = mid - 1;
} else if (nums[mid] < target) {
low = mid + 1;
} else {
if (mid === 0 || nums[mid - 1] !== nums[mid]) {
return nums.length - mid;
} else {
high = mid - 1;
}
}
}
return -1;
};
console.log(getOneCount([0, 0, 1, 1, 1, 1, 1], 1));
Top comments (0)