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

    你可以假设数组中无重复元素。

    示例 1:

    输入: [1,3,5,6], 5
    输出: 2
    示例 2:

    输入: [1,3,5,6], 2
    输出: 1
    示例 3:

    输入: [1,3,5,6], 7
    输出: 4
    示例 4:

    输入: [1,3,5,6], 0
    输出: 0

    解答:

    var searchInsert = function(nums, target) {
    for(let i=0; i if(nums[nums.length-1] < target){ // 判断最后一个值
    return nums.length
    }else if(nums[0] > target){ //判断第一个值
    return 0
    }else if(nums[i] == target){ // 判断相等的值
    return i
    }else{ // 判断两边中间插入值
    if(nums[i]target){
    return i + 1;
    }
    }
    }
    };

    1. //时间复杂度为nlog2n(补充一种解决方法)
    2. function findKey(a, val) {
    3. if (a.indexOf(val) !== -1) {
    4. console.log(a.indexOf(val))
    5. return a.indexOf(val);
    6. }
    7. //可以折半查找-确定插入位置
    8. let i = 0;
    9. let j = a.length - 1;
    10. while (i <= j) {
    11. let mid = Math.floor((i + j) / 2);
    12. if (a[mid] < val) {
    13. i = mid + 1;
    14. } else {
    15. j = mid - 1;
    16. }
    17. }
    18. for(let k = a.length - 1; k >= j + 1; k --) {
    19. a[k + 1] = a[k];
    20. }
    21. a[j + 1] = val;
    22. console.log(a, 'aaa');
    23. return a;
    24. }