leetCode 35 Search Insert Position (Binary Search) | JSer - algorithm & JavaScript

preview_player
Показать описание
leetCode 35 Search Insert Position (Binary Search)
Pretty easy problem, take care of the ending case.

Hi I'm a JavaScript engineer who is not good at algorithms,
and currently practicing leetCode online. If you are interested, maybe we can learn together.
Рекомендации по теме
Комментарии
Автор

Try this
ADD MIDDLE TO i or J

var searchInsert = function(nums, target){
i = 0;
let middle;
j = nums.length
while (i <= j ){
middle = Math.floor((i+j)/2);
if(nums[middle] === target){
return middle
}
if(nums[middle] < target){
i = middle + 1
}
else{
j = middle - 1
}
}
return i
}

robertoromagnoli
Автор

why return i, of outside the while loop

astronaut
Автор

Would setting the start or end value to the middle value make it faster?

blankversefilms
join shbcf.ru