Concise JavaScript O(log n) using binary search


  • 0
    var searchRange = function(nums, target) {
        let left = search(nums, target, 0, nums.length - 1);
        return [left, left === -1 ? -1 : search(nums, target, left, nums.length - 1, false)];
    };
    
    function search(nums, target, low, high, isLeft = true) {
        if (low > high) return -1;
        let mid = Math.floor((low + high) / 2);
        if (nums[mid] > target || nums[mid] === target && isLeft && nums[mid] === nums[mid - 1]) {
            return search(nums, target, low, mid - 1, isLeft);
        } else if (nums[mid] < target || nums[mid] === target && !isLeft && nums[mid] === nums[mid + 1]) {
            return search(nums, target, mid + 1, high, isLeft);
        }
        return mid;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.