Search Insert Position
cheatsheet1999 opened this issue · 0 comments
cheatsheet1999 commented
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.
/**
* @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;
};