Skip to content

Search Insert Position #26

Open
Open
@cheatsheet1999

Description

@cheatsheet1999

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;
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions