孙晓聪
  • 最新
  • 博客
  • 书评
  • Search Insert Position

    Descripition

    Solutions

    First Idea

    /**
     * @param {number[]} nums
     * @param {number} target
     * @return {number}
     */
    var searchInsert = function (nums, target) {
      let low = 0
      let high = nums.length - 1
    
      // only ->> [low v high] [low v, v high] ->> [low, high]
      while (low < high) {
        const middle = low + Math.floor((high - low) / 2)
        if (nums[middle] === target) {
          return middle
        }
    
        nums[middle] < target ? (low = middle + 1) : (high = middle - 1)
      }
    
      return target > nums[low] ? low + 1 : low
    }
    

    -- Time Complexity: O(logn) -- Space Complexity: O(1)