cheatsheet1999/FrontEndCollection

Search Insert Position

cheatsheet1999 opened this issue · 0 comments

Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You must write an algorithm with O(log n) runtime complexity.

Screen Shot 2021-09-09 at 1 38 36 PM

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number}
 */

//Due to the fact that "start" will always approach the target if "mid" did not match target
var searchInsert = function(nums, target) {
    let start = 0, end = nums.length - 1;
    while(start <= end) {
        let mid = Math.floor((start + end) / 2);
        if(nums[mid] === target) {
            return mid;
        } else if(nums[mid] < target) {
            start = mid + 1;
        } else if(nums[mid] > target) {
            end = mid - 1;
        }
    }
    return start;
};