searchInsert with JavaScript


  • 0
    N
    /**
     * @param {number[]} nums
     * @param {number} target
     * @return {number}
     */
    var searchInsert = function(nums, target) {
      const recursive = (arr, search) => {
        if(search > arr[arr.length - 1]) {
          return arr.length;
        } else if (search < arr[0]) {
          return 0;
        }
    
        let midIndex = (arr.length % 2 === 0) ? arr.length / 2 : (arr.length - 1) / 2;
    
        if (search === arr[midIndex]) {
          return midIndex;
        } else if (search < arr[midIndex]) {
          return recursive(arr.slice(0, midIndex), target);
        } else {
          return midIndex + recursive(arr.slice(midIndex), target);
        }
      }
      return recursive(nums, target);
    };
    

Log in to reply
 

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