- Search Insert Position
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.
[l,r]
为答案的范围,因为target
可能大于nums[n-1]
,所以l=0,r=n
m = l+(r-l)/2
避免overflownums[m] < target
,答案至少为m+1
nums[m] > target
,答案至多为m
- 考虑剩下3个、2个、1个元素的情况,当剩下1个元素时,如果
nums[m] > target
则陷入死循环,需要跳出循环,所以while
的条件为l<r
// runtime 70.90% memory 64.76%
var searchInsert = function(nums, target) {
let l = 0
let r = nums.length
while (l < r) {
const m = Math.floor(l + (r - l) / 2)
if (nums[m] == target) return m
else if (nums[m] < target) l = m + 1
else r = m
}
return l
}