41 lines
882 B
JavaScript
41 lines
882 B
JavaScript
/**
|
|
* @param {number[]} nums
|
|
* @param {number} target
|
|
* @return {number[]}
|
|
*/
|
|
const searchRange = function (nums, target) {
|
|
|
|
};
|
|
|
|
|
|
function searchRange(nums, target) {
|
|
let left = 0, right = nums.length - 1;
|
|
let start = -1, end = -1;
|
|
|
|
// Find the first occurrence
|
|
while (left <= right) {
|
|
let mid = Math.floor((left + right) / 2);
|
|
if (nums[mid] >= target) {
|
|
right = mid - 1;
|
|
} else {
|
|
left = mid + 1;
|
|
}
|
|
}
|
|
start = nums[left] === target ? left : -1;
|
|
|
|
// Find the last occurrence
|
|
left = 0;
|
|
right = nums.length - 1;
|
|
while (left <= right) {
|
|
let mid = Math.floor((left + right) / 2);
|
|
if (nums[mid] <= target) {
|
|
left = mid + 1;
|
|
} else {
|
|
right = mid - 1;
|
|
}
|
|
}
|
|
end = nums[right] === target ? right : -1;
|
|
|
|
return [start, end];
|
|
}
|