搜索插入位置
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。请必须使用时间复杂度为 O(log n) 的算法。
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with O(log n) runtime complexity.
思路:
符合二分查找的条件:
- 所有元素都是有序排列。
- 所有元素都不重复。
需要注意的是这道题返回情况有四种:
- 目标值在数组所有元素之前:return right + 1。
- 目标值等于数组中某一个元素:return middle。
- 目标值插入在数组中:return right + 1。
- 目标值在数组所有元素之后:return right + 1。
代码:
var searchInsert = function(nums, target) {
let left = 0, right = nums.length - 1;
while(left <= right){
let middle = Math.floor((right - left) / 2) + left;
if(nums[middle] === target){
return middle;
}else if(nums[middle] < target){
left = middle + 1;
}else{
right = middle - 1;
}
}
return right+1;
};