算法:搜索插入位置(js)

题目:力扣

思路:要求时间复杂度为 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
};

结果:

猜你喜欢

转载自blog.csdn.net/qq_43119912/article/details/123785556