【数组】Search Insert Position

题目:

Given a sorted array 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 may assume no duplicates in the array.

Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0

思路:

二分查找。其中特别注意的是:middle=(low+high)/ 2 ,可能会溢出,可以替换为middle = low + Math.ceil((high - low)/2)

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number}
 */
var searchInsert = function(nums, target) {
    var l=0,r=nums.length-1,middle;
    while(l<=r){
        middle=l+Math.floor((r-l)/2);
        if(nums[middle]>target){
            r=middle-1;
        }else if(nums[middle]<target){
            l=middle+1;
        }else{
            return middle;
        }
    }
    return l;
};
原文地址:https://www.cnblogs.com/shytong/p/5110210.html