Open
Description
参考题解:
- https://leetcode.cn/problems/search-insert-position/solution/sou-suo-cha-ru-wei-zhi-by-leetcode-solution/
- https://leetcode.cn/problems/search-insert-position/solution/te-bie-hao-yong-de-er-fen-cha-fa-fa-mo-ban-python-/
function searchInsert(nums: number[], target: number): number {
// 二分法, 建议画图理解
let left = 0;
let right = nums.length - 1;
while (left <= right) {
// 中间节点, 这边使用向下取整
let mid = Math.floor((right + left) / 2);
// 相等, 找到目标值
if (nums[mid] === target) {
return mid;
} else if (nums[mid] < target) { // 目标值比中间值大, 需要左边的位置右移
left = mid + 1; // left 就是将要返回的值 (将会被按顺序插入的位置)(下一次二分比较的左边位置)
} else if (nums[mid] > target) { // 否则右边的位置左移
right = mid - 1;
}
}
return left;
}