Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Search Insert Position #26

Open
cheatsheet1999 opened this issue Sep 9, 2021 · 0 comments
Open

Search Insert Position #26

cheatsheet1999 opened this issue Sep 9, 2021 · 0 comments

Comments

@cheatsheet1999
Copy link
Owner

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;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant