Javascript solution (Beats 91%)


  • 0
    R
    var searchRange = function(nums, target) {
        var bottomP,
            upperP;
        
        bottomP = binarySearch(nums, target);
        
        if(bottomP === -1)
            return [-1,-1];
        
        upperP = bottomP;
        upperP++;
        bottomP--;
        
        while(nums[upperP] === target || nums[bottomP] === target){
            if(nums[upperP] === target)
                upperP++;
            if(nums[bottomP] === target)
                bottomP--;
        }
        
        return [++bottomP, --upperP];
        
    };
    
    var binarySearch = function(arr, target){
        var actual = 1,
        	lower = 0,
        	upper = arr.length;
        
        while(lower <= upper){
            actual = Math.floor((upper + lower) / 2);
            
            if(arr[actual] > target){
                upper = actual - 1;
            }else if(arr[actual] < target){
                lower = actual + 1;
            }else{
                if(arr[actual] === target)
                	return actual;
                else
                	return -1;
            }
        }
        
        return -1;
    };

Log in to reply
 

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