JavaScript solution - recursion


  • 0
    K
    /**
     * @param {number[]} nums
     * @param {number} target
     * @return {number[]}
     */
    var searchRange = function(nums, target) {
        return findTarget(nums, target, 0, nums.length -1) || [-1, -1];
    };
    
    function findTarget(nums, target, s, e){
    
        /***
        if the value at start is greater than the tartget then this sub section can be discarded
        if the value at the end is less than the target then this can also be thrown out.
        **/
        var indx = null;
        var res = [];
        if(nums[s]> target || nums[e] < target) return null;
        if(nums[s]===target)indx=s;
        if(nums[e]===target)indx=e;
        if(indx!==null){
            //find start;
              for(var i=indx-1;; i--){
                    if(nums[i]!==target){
                        res.push(i+1);
                        break;
                    }
                }
    
            //find end
              for(var i=indx+1;; i++){
                    if(nums[i]!==target){
                        res.push(i-1);
                        break
                    }
                }
    
                return res;
        }
        if(e-s <= 1)return null;
        indx = Math.floor((s+e)/2);
        return findTarget(nums, target, s, indx) || findTarget(nums, target, indx, e)
    
    }
    

Log in to reply
 

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