Search Insert Position

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


var searchInsert = function(nums, target) {
    var temp;
    if(target <= nums[0]){
        return 0;
    }else if(target === nums[nums.length -1]){
        return nums.length-1;
    }else if(target > nums[nums.length - 1] ){
        return nums.length;
    }else{
        for(var i = 0,len = nums.length; i < len; i++){
            temp = nums[i];
            if(target <= temp){
                return i; 
            }
        }
    }
};

判断,因为数组排过序了,所以,判断,是否小于数组头部的元素,大于数组尾部元素,中间比较大小取位置。

发表评论

电子邮件地址不会被公开。 必填项已用*标注