35. Search Insert Position

202409292215
tags: #binary-search

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

Reference

https://leetcode.com/problems/search-insert-position/