algorighm/binary-search/35搜索插入位置.js

37 lines
864 B
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
const searchInsert = function (nums, target) {
};
/*
直接使用二分查找二分查找没什么好说的但是这个题目中target不一定存在nums中所以需要设置一个pos遍历来保存target应该插入的位置
我们只需在target < nums[mid]的时候设置一次就行初始化pos的index=nums.length
*/
function f2(nums, target) {
let pos = nums.length;
let left = 0;
let right = nums.length - 1;
// 二分查找知道left>right结束查找
while (left <= right) {
const mid = Math.floor((left + right) / 2);
// 如果target<nums[mid] 则更新pos
if (target === nums[mid]) return mid;
if (target < nums[mid]) {
pos = mid;
right = mid - 1;
continue;
}
left = mid + 1;
}
return pos;
}