题目:力扣
思路:要求时间复杂度为 O(log n)就要使用二分查找了
。
代码:
var searchInsert = function(nums, target) {
let left = 0, right = nums.length - 1
while (left <= right) {
const temp = Math.floor((left + right) / 2)
if (nums[temp] === target) {
return temp
} else if (nums[temp] > target) {
right = temp - 1
} else {
left = temp + 1
}
}
return left
};
结果: