搜索插入位置

85 阅读1分钟

搜索插入位置

给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。


var searchInsert = function (nums, target) {
    const len = nums.length
    for (var i = 0; i < len; i++) {

        if (target < nums[0]) {
            return 0
        } else if (target > nums[len - 1]) {
            return len
        } else if (nums[i] === target) {
            return i
        } else if (target > nums[i] && target < nums[i + 1]) {
            return i + 1
        }
    }
};